2

I have created my own collection and implemented INotifyCollectionChanged.

public class ObservableSortedSet<T> : SortedSet<T>, INotifyCollectionChanged
{
    public event NotifyCollectionChangedEventHandler CollectionChanged;

    public new bool Add(T item)
    {
        var result = base.Add(item);
        if (result)
            CollectionChanged?.Invoke(item,
                new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item));
        return result;
    }

    public new bool Remove(T item)
    {
        var result = base.Remove(item);
        if (result)
            CollectionChanged?.Invoke(item,
                new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, item));
        return result;
    }

    public new void Clear()
    {
        base.Clear();
        CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
    }
}

However when I try to use this collection as ItemsSource in views, they do not update automatically when I e.g. remove an item. As I seen in other questions here, I should implement INotifyCollectionChanged. I did this and yet it doesn't work. Any suggestions?

1 Answers1

2

The reason why your remove method does not work is that you have to add the index of the removed element.

I tried it this way and it does work:

View codebehind:

public ObservableSortedSet<String> Values { get; private set; }

    public MainWindow()
    {
        InitializeComponent();
        DataContext = this;

        Values = new ObservableSortedSet<string>();
        Values.Add("Test0");
        Values.Add("Test1");
        Values.Add("Test2");
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        Values.Add("Test" + Values.Count);
    }
}

View:

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="*" />
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>

    <ListView ItemsSource="{Binding Path=Values}">
        <ListView.ItemTemplate>
            <DataTemplate>
                <Label Content="{Binding}" />
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>

    <Button Grid.Row="1" Content="Add" Click="Button_Click"/>
</Grid>
wake-0
  • 3,918
  • 5
  • 28
  • 45