0

我有一些表(使用 ListView),如果选中了某个复选框,我想在表中显示一些对象(制作过滤器)....(如果未选中该复选框,我想显示所有表项)

我如何使用 mvvm 来做到这一点?我无法使用包含 xaml 的 .cs 文件。

谢谢

4

2 回答 2

2

您可以在 ViewModel 中绑定复选框的 IsChecked 属性。在属性设置器中,您可以过滤绑定到 ListView 的集合。

XAML:

<CheckBox IsChecked="{Binding IsChecked}"/>

视图模型:

private bool _isChecked;
public bool IsChecked
{
   get
   {
     return _isChecked; 
   }
   set
   {
     _isChecked = value;
     //filer your collection here
   }
}
于 2012-08-30T06:38:26.013 回答
2

这是一个小例子,它是如何工作的

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));
        }
    }
}

编辑 一个完整的例子在这里

希望有帮助

于 2012-08-30T07:06:02.137 回答