wpf mvvm datagrid数据过滤

datagrid数据过滤,你可以通过设置RowStyle属性,通过将Visibility绑定到ViewModel层的属性来控制是否可见,比如:

<DataGrid.RowStyle>
    <Style TargetType="{x:Type DataGridRow}">
        <Setter Property="Visibility">
            <Setter.Value>
                <MultiBinding 
                Converter="{StaticResource DataGridRowVisibilityConverter}">
                    <Binding ElementName="dataGrid" 
                            Path="DataContext.CurrentType"/>                
                    <Binding Path="Type"/>
                </MultiBinding>
            </Setter.Value>
        </Setter>
    </Style>
</DataGrid.RowStyle>

这里我利用DataGridRowVisibilityConverter这个转换器,当CurrentType=“all”时所有的都显示,当CurrentType不是all时,要求datagrid数据源里面某个数据的Type值和CurrentType一致,才显示。

但是这样做有一个问题,就是当行的可见性变更后,数据并不会重刷,datagrid的row索引还是老的,需要手动刷新,但是我们是mvvm模式,没法手动刷新datagrid的数据。我暂时还没找到解决这个问题的方法。

针对过滤,其实官方提供了一个解决方案,就是利用ICollectionView。该接口包含了一个Refresh方法,同时包含一个filter属性,该属性是用来过滤的,使用的时候,后台数据这么写:

public ICollectionView ViewSource { set; get; }

在ViewModel的构造方法里面这么写:

ViewSource = 
System.Windows.Data.CollectionViewSource.GetDefaultView(GlobalData.StatusList);
ViewSource.Filter = new Predicate<object>(OnFilterMovie);
bool OnFilterMovie(object item)
{
    if (CurrentType == "all") return true;
    else return (item as MovieModel).Type == CurrentType;
}

然后CurrentType属性这么写,当变更时,调用ViewSource的Refresh方法刷新一次数据

private string currentType = "all";
public string CurrentType
{
    get => currentType;
    set
    {
        if (currentType != value)
        {
            currentType = value;
            ViewSource.Refresh();
        }
    }
}

而前端绑定还按照普通绑定的方法写就可以了:

 

<DataGrid SelectedItem="{Binding SelectedItem}" ItemsSource="{Binding ViewSource}">

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值