WPF:动态过滤dataGrid

时间:2017-02-14 17:15:05

标签: c# wpf xaml mvvm datagrid

在我的WPF Window中,我有一个DataGrid控件,其ItemsSource绑定到一个ObservableCollection项(让我们说一个带有几个属性的简单对象):

XAML: (为简洁起见删除了一些xmlns内容)

<Window>
    <Window.Resources>
        <CollectionViewSource x:Key="MyViewSource"
                              Source="{Binding MyItemList}"
                              Filter="MyItemList_Filter"/>
    </Window.Resources>

    <Window.DataContext>
        <!-- Some Ioc stuff -->
    </Window.DataContext>

    <StackPanel>
        <TextBox Text="{Binding TextFilter}" />
        <DataGrid Grid.Row="1" x:Name="dataGrid"
            ItemsSource="{Binding Source={StaticResource MyViewSource}}"
            SelectionUnit="FullRow"
            SelectionMode="Extended"
            CanUserAddRows="False"
            CanUserDeleteRows="False"
            HeadersVisibility="Column" />
    </StackPanel>
</Window>

ViewModel(cs):

public class ViewModel : ViewModelBase // From Galasoft MVVM Light toolkit
{

    #region TextFilter Property
    public const string TextFilterPropertyName = "TextFilter";

    private string _TextFilter;

    public string TextFilter
    {
        get
        {
            return _TextFilter;
        }

        set
        {
            if (_TextFilter == value)
            {
                return;
            }

            _TextFilter = value;

            RaisePropertyChanged(TextFilterPropertyName);
        }
    }
    #endregion // TextFilter Property

    #region MyItemList Property
    public const string MyItemListPropertyName = "MyItemList";

    private ObservableCollection<Item> _MyItemList;

    public ObservableCollection<Item> MyItemList
    {
        get
        {
            return _MyItemList;
        }

        set
        {
            if (_MyItemList == value)
            {
                return;
            }

            _MyItemList = value;

            RaisePropertyChanged(MyItemListPropertyName);
        }
    }
    #endregion // MyItemList Property


}

过滤方法,来自 Window的代码:

private void MyItemList_Filter(object sender, FilterEventArgs e)
{
    var vm = (ViewModel)this.DataContext;
    var item = (Item)e.Item;
    // ...Simplified...
    e.Accepted = item.PropertyToCheck.Contains(vm.TextFilter);
}

仅在填充MyItemList时应用过滤:如何在“实时”MyItemList_Filter更改时调用TextFilter(并相应地显示/隐藏DataGrid项目?)

任何帮助将不胜感激

2 个答案:

答案 0 :(得分:3)

您可以(应该)将过滤逻辑移动到视图模型,例如:

docker run -d --net mynet1 --ip 172.18.0.11 --hostname rab1 --add-host rab2:172.18.0.12 --name rab1con -p 15672:15672 rabbitmq:3-management

它所属的地方。那么你不需要CollectionViewSource:

docker run -d --net mynet1 --ip 172.18.0.12 --hostname rab2 --add-host rab1:172.18.0.11 --name rab2con -p 15673:15672 rabbitmq:3-management

答案 1 :(得分:0)

现在可以使用 NuGet 包 DataGridExtensions 来实现这一点。

Filtering a WPF datagrid using DataGridExtensions