[英]How to filter table item by binding to checkbox ?
我有一些表(使用ListView),如果要选中某些复选框,我想在表中显示某个对象(使过滤器)....(如果未选中该复选框,我想显示所有表项)
我如何使用mvvm做到这一点? 我无法使用xaml背后的.cs文件。
谢谢
您可以在ViewModel中绑定复选框的IsChecked属性。 在prpoperty setter中,您可以过滤绑定到ListView的集合。
XAML:
<CheckBox IsChecked="{Binding IsChecked}"/>
视图模型:
private bool _isChecked;
public bool IsChecked
{
get
{
return _isChecked;
}
set
{
_isChecked = value;
//filer your collection here
}
}
这是一个小例子,它如何工作
xaml上的代码,绑定到FilterItems属性
<CheckBox Content="should i filter the view?" IsChecked="{Binding FilterItems}" />
<ListView ItemsSource="{Binding YourCollView}" />
模型视图中的代码
public class MainModelView : INotifyPropertyChanged
{
public MainModelView()
{
var coll = new ObservableCollection<YourClass>();
yourCollView = CollectionViewSource.GetDefaultView(coll);
yourCollView.Filter += new Predicate<object>(yourCollView_Filter);
}
bool yourCollView_Filter(object obj)
{
return FilterItems
? false // now filter your item
: true;
}
private ICollectionView yourCollView;
public ICollectionView YourCollView
{
get { return yourCollView; }
set
{
if (value == yourCollView) {
return;
}
yourCollView = value;
this.NotifyPropertyChanged("YourCollView");
}
}
private bool _filterItems;
public bool FilterItems
{
get { return _filterItems; }
set
{
if (value == _filterItems) {
return;
}
_filterItems = value;
// filer your collection here
YourCollView.Refresh();
this.NotifyPropertyChanged("FilterItems");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String propertyName)
{
var eh = PropertyChanged;
if (eh != null) {
eh(this, new PropertyChangedEventArgs(propertyName));
}
}
}
编辑一个完整的例子在这里
希望能有所帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.