问题
I want to make an WPF app for browsing recipes for dishes. Having trouble with filtering data.
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.
Here is my XAML binding:
<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# 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();
}
}
回答1:
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}"
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=...}
来源:https://stackoverflow.com/questions/61209535/filtering-icollectionview-binded-to-itemscontrol