列表框基于TextBox值排序

时间:2015-03-27 19:39:01

标签: c# wpf mvvm

如何使用TextBox输入值对ListBox项进行排序。 匹配案例ListBox项目显示列表框的顶部 这是我的代码

XAML

<Grid>
    <TextBox HorizontalAlignment="Left" Height="23" Margin="67,39,0,0" TextWrapping="Wrap" Text="{Binding CustomerSort,UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Top" Width="120"/>
    <ListBox Margin="67,79,185,26" Background="LightYellow"
            DisplayMemberPath="Name" ItemsSource="{Binding CustomerColloction}"/>
</Grid>

C#代码

 public class Customers
{
    public String Name { get; set; }
    public Int32 Age { get; set; }
}

public class ViewModel
{
    public ViewModel()
    {
        CustomerColloction = new ObservableCollection<Customers>();
        CustomerColloction.Add(new Customers() { Name = "AAA", Age = 25 });
        CustomerColloction.Add(new Customers() { Name = "AA", Age = 25 });
        CustomerColloction.Add(new Customers() { Name = "BBB", Age = 26 });
        CustomerColloction.Add(new Customers() { Name = "BB", Age = 24 });
        CustomerColloction.Add(new Customers() { Name = "AAAA", Age = 13 });
        CustomerColloction.Add(new Customers() { Name = "BB", Age = 11 });
        CustomerColloction.Add(new Customers() { Name = "XYZ", Age = 44 });
    }
    public ObservableCollection<Customers> CustomerColloction { get; set; }

    private String _CustomerSort = String.Empty;
    public String CustomerSort
    {
        get
        {
            return _CustomerSort;
        }
        set
       {
            _CustomerSort = value;
            NotifyPropertyChanged("CustomerSort");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected void NotifyPropertyChanged(string propertyName)
    {
        if (this.PropertyChanged != null)
            this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

我想得到的结果就像我们在TextBox中输入AA,显示排序项目表单列表框

  • AA
  • AAA
  • AAAA
  • BB
  • BB
  • BBB
  • XYZ

2 个答案:

答案 0 :(得分:1)

设置组合框并设置下拉模式
最好对可观察集合进行排序并设置为ListBox CustomerColloction.OrderBy(q =&gt; q.Name).ToList();

答案 1 :(得分:0)

我可以看到它是一个相当的vauge要求,但只是为了给你一个想法,你可以像这样操纵你的绑定对象集合来实现类似的结果

以下代码已由移动设备输入,且未经过验证..

CustomerColloction.Where(p=>p.name.Contains(CustomerSort)).OrderBy(q=>q.Name).ToList().Add(CustomerColloction.where(r=>r.name.Contains(CustomerSort)=false).OrderBy(s=>s.Name).toList()

在你的setter中,CustomerSort属性会为你绑定集合提出通知