【问题标题】:Filtering ICollectionView binded to ItemsControl过滤 CollectionView 绑定到 ItemsControl
【发布时间】:2020-04-14 14:01:07
【问题描述】:

我想制作一个 WPF 应用程序来浏览菜谱。过滤数据时遇到问题。

我正在使用 ItemsControl 使我的数据在窗口中看起来像“图块”。现在我想用 TextBox 过滤它,但我不知道出了什么问题。

这是我的 XAML 绑定:

<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# 代码

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

    }
}

【问题讨论】:

    标签: c# wpf xaml itemscontrol


    【解决方案1】:

    this.DataContext = ItemsView; - 使用这种 DataContext 绑定 Text="{Binding Szukane}" 不可能工作,因为 Szukane 不是 ItemsView 的属性。您需要更改绑定源:

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

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-30
      • 1970-01-01
      • 1970-01-01
      • 2013-04-05
      • 2011-06-30
      • 1970-01-01
      • 1970-01-01
      • 2014-09-24
      相关资源
      最近更新 更多