0

I have an ObservableCollection of objects of a certain class. When I assign it a new value my CollectionChanged is null and UI don't update. If I in constructor set beginning items to Collection like this:

    public TabPageViewModel()
    {
        tabPageDatas = new ObservableCollection<TabPageDataModel>
        {
            new TabPageDataModel(null, "test1"),
        };

    }

Then at start my app I see new TabItem, but if I set new value, then no.

public class TabPageViewModel : INotifyCollectionChanged
{
    public ObservableCollection<TabPageDataModel> TabPageDatas
    {
        get => tabPageDatas;
        set
        {
            CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add));
        }
    }

    private ObservableCollection<TabPageDataModel> tabPageDatas;

    public TabPageViewModel()
    {
        tabPageDatas = new ObservableCollection<TabPageDataModel>();
    }

    public event NotifyCollectionChangedEventHandler CollectionChanged;
}



private void AddNewTabItem_Click(object sender, RoutedEventArgs e)
{    
    ObservableCollection<TabPageDataModel> newTab = tabPageViewModel.TabPageDatas;
    newTab.Add(new TabPageDataModel(bitmapImage, "Test2");
    tabPageViewModel.TabPageDatas = newTab;
}

XAML:

<TabControl ItemsSource="{Binding Path=TabPageDatas, Mode=TwoWay}">
        <TabControl.DataContext>
            <ViewModels:TabPageViewModel/>
        </TabControl.DataContext>
Jorr1
  • 11
  • 6
  • You have to implement INotifyPropertyChanged instead of INotifyCollectionChanged. The latter is already implemented by the ObservableCollection class. Also make sure to set the backing field of the property, i.e. `tabPageDatas = value;` before firing the PropertyChanged event. – Clemens May 03 '22 at 19:57
  • And setting `Mode=TwoWay` on an ItemsSource Binding is pointless. Such a Binding is always implicitly OneWay. – Clemens May 03 '22 at 19:59
  • I add inheritance from interface INotifyPropertyChanged and to set add `tabPageDatas = value;` and invoke event, but this is too null. I deleted `Mode=TwoWay`. ` public ObservableCollection TabPageDatas { get => tabPageDatas; set { tabPageDatas = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(TabPageDatas))); } }` – Jorr1 May 03 '22 at 20:16
  • Also ensure that `tabPageViewModel` is assigned to the view's DataContext. The XAML declaration assigns a different instance to the DataContext. – Clemens May 03 '22 at 22:39
  • I add in MainWindow constructor ` TCTabs.ItemsSource = tabPageViewModel.TabPageDatas;` and now work but I don't understand why it's work. – Jorr1 May 04 '22 at 06:53
  • You should have set `DataContext = tabPageViewModel;` and remove the DataContext assignment from XAML. – Clemens May 04 '22 at 07:40

0 Answers0