筛选绑定到ItemsControl的ICollectionView [英] Filtering ICollectionView binded to ItemsControl

查看:44
本文介绍了筛选绑定到ItemsControl的ICollectionView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想制作一个WPF应用程序来浏览菜谱.过滤数据时遇到麻烦.

I want to make an WPF app for browsing recipes for dishes. Having trouble with filtering data.

我正在使用ItemsControl使我的数据在窗口中看起来像平铺".现在,我想使用TextBox对其进行过滤,但是我无法弄清楚出了什么问题.

I'm using ItemsControl to make my data look like "tiles" in the window. Now i want to filter it with TextBox, but I cant figure what is wrong.

这是我的XAML绑定:

Here is my XAML binding:

<ItemsControl ItemsSource="{Binding}" Height="573">

文本框:

<TextBox x:Name="Szukaj" Text="{Binding Szukane, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Left" Height="27.667" Margin="18.667,145,0,0" IsEnabled="True" TextWrapping="Wrap" VerticalAlignment="Top" Width="197.333" FontSize="14" />

具有过滤功能的C#代码

C# code with filtering

public ObservableCollection<Przepis> lista {get; set; }

public ICollectionView ItemsView
{
    get { return CollectionViewSource.GetDefaultView(lista); }
}

public Page1(ObservableCollection<Przepis> l)
{
    InitializeComponent();
    lista = l;

    ItemsView.Filter = new Predicate<object>(o => Filter(o as Przepis));
    this.DataContext = ItemsView;
}

private bool Filter(Przepis p)
{
    return Szukane == null
        || p.NazwaPrzepisu.IndexOf(Szukane, StringComparison.OrdinalIgnoreCase) != -1
        || p.RodzajDiety.IndexOf(Szukane, StringComparison.OrdinalIgnoreCase) != -1
        || p.RodzajPosilku.IndexOf(Szukane, StringComparison.OrdinalIgnoreCase) != -1;
}

private string szukane;

public string Szukane
{
    get { return szukane; }
    set
    {
        szukane = value;
        NotifyPropertyChanged("Szukane");
        ItemsView.Refresh();

    }
}

推荐答案

this.DataContext = ItemsView;-带有这样的DataContext绑定Text="{Binding Szukane}"可能无法工作,因为Szukane不是ItemsView的属性.您需要更改绑定源:

this.DataContext = ItemsView; - with such DataContext binding Text="{Binding Szukane}" cannot possibly work, bacause Szukane is not a property of ItemsView. you need to change binding source:

Text="{Binding Szukane, RelativeSource={RelativeSource AncestorType=Page} UpdateSourceTrigger=PropertyChanged}"

或者创建一个同时包含ItemsView属性和Szukane属性的视图模型,并将其用于DataContext.

Alternatively create a view model, with contains both ItemsView and Szukane properties, and use it for DataContext.

我还建议为文本绑定添加延迟,以减少键入时的过滤量:

I also recommend to add a delay for Text binding to reduce amount of filtering while typing:

Text="{Binding Szukane, Delay=250, RelativeSource=...}

这篇关于筛选绑定到ItemsControl的ICollectionView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆