我想制作一个 WPF 应用程序来浏览菜肴食谱。过滤数据时遇到问题。
我正在使用 ItemsControl 使我的数据在窗口中看起来像“图块”。现在我想用 TextBox 过滤它,但我不知道出了什么问题。
这是我的 XAML 绑定:
<ItemsControl ItemsSource="{Binding}" Height="573">
Textbox:
<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();
}
}
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=...}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)