Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ItemsSource binding and not working PropertyChanged

I set DataContext:

this.DataContext = new MainWindowViewModel();

And I am binding the ItemsSource of a TabControl, when I add a new TabItem in the contructor of MainWindowViewModel it is working! But when I add a new TabItem in an event (Click) there is no effect.

I have this property:

List<Item> _listOfItem;
public List<Item> ListOfItem
{
    get
    {
        return _listOfItem;

    }
    set
    {
        _listOfItem = value;
        PropertyChanged(this, new PropertyChangedEventArgs("ListOfItem"));
    }
}

Please help.

like image 860
Never Avatar asked Jun 09 '26 12:06

Never


1 Answers

You should use an ObservableCollection, rather than a List if you wish the UI to be notified of collection changes.

ObservableCollection<Item> _listOfItem;
public ObservableCollection<Item> ListOfItem
{
    get
    {
        return _listOfItem;
    }
    set
    {
        _listOfItem = value;
        PropertyChanged(this, new PropertyChangedEventArgs("ListOfItem"));
    }
}

Note that you only need to invoke the PropertyChanged event for your ListOfItem if the reference changes after construction of your view model type. If it doesn't change, then a simple auto property will suffice for ListOfItem.

like image 124
devdigital Avatar answered Jun 11 '26 04:06

devdigital



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!