Sturm
Sturm

Reputation: 4125

Filter collection issue

I have a ComboBox with a collection of custom objects bound to it:

<ComboBox ItemsSource="{Binding CreatedMacros}" Width="150" Height="25"  
          HorizontalAlignment="Left" Margin="10"                                
          DisplayMemberPath="Name"
          SelectedItem="{Binding SelectedMacro}"/>

In some other place I have an ItemsControl with a View bound to it:

<ItemsControl x:Name="stackMacros" ItemsSource="{Binding ViewMacros}">

Where the view is defined this way:

    private ICollectionView _viewMacros;
    public ICollectionView ViewMacros
    {
        get
        {
            return _viewMacros;
        }
        set
        {
            _viewMacros = value;
            RaisePropertyChanged("ViewMacros");
        }
    }

And intialized and filtered like this:

         ViewMacros = CreatedMacros as ICollectionView;
         ViewMacros = CollectionViewSource.GetDefaultView(CreatedMacros);

         ViewMacros.Filter = delegate(object o)
         {
             if (((Macro)o).PrivateMacro== false)
             {
                 return true;
             }
             return false;
         };

The issue is that at both places I get the filtered results. My aim is to edit some macros in the editor, and display them as buttons in other place. But only non-private macros should be there, that's why I'm using the filter, distinguishing with the PrivateMacro property.

How could I display in the ComboBox the whole collection and in the ItemsControl only the filtered results?

Upvotes: 0

Views: 79

Answers (1)

Rohit Vats
Rohit Vats

Reputation: 81253

Instead of getting defaultView over source collection, create new CollectionViewSource and assign its view to ViewMacros if you don't want the sorting and filtering in original source collection -

ViewMacros = new CollectionViewSource() { Source = CreatedMacros }.View; 

UPDATE

When you bind to any collection say ObservableCollection, WPF binding engine internally creates a View on top of your collection and bind to that. It can be ListCollectionView or other dervied versions of ICollectionView.

Remember that we never bind directly to the collection; there is always a view on top of that collection that we bind to. If you are not providing any view, default view is created behind the scenes.

So, when you ask for CollectionViewSource.GetDefaultView(), it will return the view which it has created internally over that collection. Hence any filtering and sorting will be applied on same collection sine both are referring to same view.

Upvotes: 3

Related Questions