WPF绑定CombobBoxItem基于属性

时间:2018-03-05 17:49:43

标签: wpf combobox binding

我的View Model课程:

class Student : INotifyPropertyChanged
    {
      private string name;       
      private bool isVisible;
      public event PropertyChangedEventHandler PropertyChanged;

      public string PersonName
      {
          get { return name; }
          set
          {
              name = value;
              OnPropertyChanged("PersonName");
          }
      }

      public bool IsVisible
      {
          get { return isVisible; }
          set
          {
              isVisible = value;
              OnPropertyChanged("IsVisible");
          }
      }
    }

我的学生collection存储了我的所有objects

public ObservableCollection<Student> Students { get; set; }

XAML:

<ComboBox x:Name="cbStudents" 
          ItemsSource="{Binding Students}"
          SelectionChanged="cbInterfaces_SelectionChanged"/>

所以在某些时候我想从我的ComboBox消失几个学生,所以我只需将IsVisible值更改为False

知道如何使用XAML吗?

1 个答案:

答案 0 :(得分:3)

您可以让您的学生集合仅返回可见学生。

    //All students (visible and invisible)
    ObservableCollection<Students> _AllStudents = GetAllStudentsFromDataSource();

    //only visible students
    ObservableCollection<Students> _VisibleStudents = new ObservableCollection<Students>();

    foreach(var _s in _AllStudents.Where(x => x.IsVisible)){
         _VisibleStudents.Add(_s);
    }

    //your property
    public ObservableCollection<Student> Students { get{ return _VisibleStudents; } }

如果您的复选框切换了学生的可见性,您的复选框可以绑定到这样的命令:

<Checkbox IsChecked="{Binding IsCheckboxChecked}" Command={Binding ToggleStudents}" />

您的视图模型对复选框切换和命令有一个额外的控制:

    bool _IsCheckboxChecked = false;
    public bool IsCheckboxChecked { 
           get { return _IsCheckboxChecked;}
           set {
                  if(_IsCheckboxChecked != value)
                  {
                    _IsCheckboxChecked = value;
                  }
               }
      }

public ICommand ToggleStudents
{
    get;
    internal set;
}

private void ToggleStudentsCommand()
{
    ToggleStudents = new RelayCommand(ToggleStudentsExecute);
}

public void ToggleStudentsExecute()
{
     _VisibleStudents.Clear();
    if(_IsCheckboxChecked){
        foreach(var _s in _AllStudents.Where(x => x.IsVisible)){
          _VisibleStudents.Add(_s);
        }
      }
    else
    {
       foreach(var _s in _AllStudents.Where(x => x.IsVisible == false)){
          _VisibleStudents.Add(_s);
        }
     }

    OnPropertyChanged("Students");

}

你的xaml不需要改变。