我是WPF的新手,我想制作一个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();
}
}
this.DataContext = ItemsView;
-使用此类DataContext绑定Text="{Binding Szukane}"
可能无法工作,因为Szukane不是ItemsView的属性。您需要更改绑定源:
Text="{Binding Szukane, RelativeSource={RelativeSource AncestorType=Page} UpdateSourceTrigger=PropertyChanged}"
或者创建一个同时包含ItemsView和Szukane属性的视图模型,并将其用于DataContext。
我还建议为文本绑定增加延迟,以减少键入时的过滤量:
Text="{Binding Szukane, Daley=250, RelativeSource=...}