Search code examples
c#wpfgridviewitemssource

WPF C# How to select between two collection to use in a GridView based on buttons active


I want to be able to bind two different collection NewItems and OldItems QueryAbleCollection as ItemsSource depending on which radiobutton is active,

let's say we have a button called NewItems and OldItems and each button should change which collection the Itemssource in the GridView should use.

How can I achieve this in the easiest way with XAML and C# ViewModel?

Under is my attempt, but I'm not sure if the smartest thing is to assign SelectedCollection another collection. Can someone correct me if this is a good approach or suggest a better approach? Right now I'm having two buttons which just trigged the isOldItems between true and false.

    private bool isOldItems;
    public bool isOldItems
    {
        get
        {
            return this.isOldItems;
        }
        set
        {
            this.isOldItems= value;
            this.OnPropertyChanged("isOldItems");
            this.OnPropertyChanged("SelectedCollection");
        }
    }


    private QueryableCollectionView _selectedCollection;
    public QueryableCollectionView SelectedCollection
    {
        get
        {
            if (isOldItems== true)
                return SelectedCollection= this.OldItemsCollection;
            else
                return SelectedCollection= this.NewItemsCollection;
        }
        set
        {
            if (this._selectedCollection!= value)
            {
                this._selectedCollection= value;
                this.OnPropertyChanged("SelectedCollection");
            }
        }
    }

Solution

  • I see no obvious huge downside with what you're doing if these are collections of the same type. Broadly speaking anyhow.

    That's a reference you're setting so if you set SelectedCollection to NewItemsCollection then it's pointing to NewItemsCollection. Add an item to SelectedCollection and you add to NewItemsCollection ( or whichever it's set to).

    BUT The if check you have will mean it never sets the backing variable and raises propertychanged from setter. Objects of the same type are always equal unless you override equals. Your

    if (this._selectedCollection!= value)
    

    Is not going to check every item in the collection and see if they're different, or the name of the thing you set. What it will do is compare types. These will presumably always be equal.

    Remove that if check out the setter.