Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stopping ItemsControls from sharing filters

Tags:

c#

wpf

xaml

I have two ItemsControls, one a ListView, and one a custom control I am developing.

I have set the ItemsControl.ItemsSource property of both controls to the same IEnumerable object, in this case, a List.

I apply a filter to the ItemsControl.Items property of my custom control (this.Items.Filter = myFilter) and my control refreshes as expected, showing only the items that match the filter.

However, the ListView using the same IEnumerable object for its ItemsControl.ItemsSource property also refreshes, showing only the items that match the filter I applied to my custom control.

Can anyone tell me how to keep the filter in my custom control from affecting the items in my listview?

like image 902
Josh Avatar asked Nov 05 '22 20:11

Josh


1 Answers

The first thing I can think of, that doesn't require any bigger modifications to what you described is to just to wrap the ItemsSource collections in a CollectionViewSource in your XAML where they are being assigned.

<DockPanel>

    <Button DockPanel.Dock="Top"
            Content="Filter Lowercase Names"
            Click="OnFilterClick"/>

    <ListView x:Name="uiListView">
        <ListView.Resources>
            <CollectionViewSource x:Key="ItemsCollection"
                                  Source="{Binding Names}" />
        </ListView.Resources>
        <ListView.ItemsSource>
            <Binding Source="{StaticResource ItemsCollection}" />
        </ListView.ItemsSource>
    </ListView>

    <ListBox x:Name="uiListBox"
             ItemsSource="{Binding Names}" />

</DockPanel>

And then the filtering logic:

public partial class Window1 : Window
{
    public Window1()
    {
        InitializeComponent();

        Names = new List<string>();

        Names.Add("Robert");
        Names.Add("Mike");
        Names.Add("steve");
        Names.Add("Jeff");
        Names.Add("bob");
        Names.Add("Dani");

        this.DataContext = this;
    }
    public List<String> Names { get; set; }

    private void OnFilterClick(object sender, RoutedEventArgs e)
    {
        uiListView.Items.Filter = x => x.ToString()[0] == x.ToString().ToUpper()[0];
    }
}
like image 105
rmoore Avatar answered Nov 14 '22 22:11

rmoore