enenkey
enenkey

Reputation: 1271

ListView not updating when ObservableCollection is replaced

I can not understand why the ListView is not refreshing when the ObservableCollection is replaced (with new one) and not changed (added or removed items). I respected all requirements for property notifications, since I'm using a DependencyObject for my view model, and SetValue is called when the collection is replaced .

I have a WPF ListView bound to a Col property of my view model:

public class ViewModel1 : DependencyObject
{
    public ViewModel1()
    {
        Col = new ObservableCollection<string>(new[] { "A", "B", "C", "D" });
    }

    protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
    {
        base.OnPropertyChanged(e);
        Debug.WriteLine("Property changed "+ e.Property.Name);
    }   

    public ObservableCollection<string> Col
    {
        get { return (ObservableCollection<string>)GetValue(ColProperty); }
        set { SetValue(ColProperty, value); }
    }

    // Using a DependencyProperty as the backing store for MyProperty.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty ColProperty =
        DependencyProperty.Register("ColProperty", typeof(ObservableCollection<string>), typeof(ViewModel1), new PropertyMetadata(null));

}

The XAML is like:

<Window x:Class="BindingPOC.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <StackPanel>
            <ListView Margin="0,10,0,0" ItemsSource="{Binding Col}" />
            <Button Click="Button_Click" >click</Button>
        </StackPanel>

    </Grid>
</Window>

So with this code, everything work fine if I don't replace the initial ObservableCollection. But when I click on the button. I replace the list with:

 private void Button_Click(object sender, RoutedEventArgs e)
        {
            (DataContext as ViewModel1).Col = new System.Collections.ObjectModel.ObservableCollection<string>(new[] { "Z", "ZZ" });

        }

The PropertyChanged method on the view model is called for Col, but the ListView is not updating its content.

Do I need to conserve the same ObservableCollection reference ? why ?

Upvotes: 3

Views: 494

Answers (1)

Thomas Levesque
Thomas Levesque

Reputation: 292345

This is because your dependency property registration is incorrect. The name of the property passed to the Register method should be "Col", not "ColProperty":

public static readonly DependencyProperty ColProperty =
    DependencyProperty.Register("Col", typeof(ObservableCollection<string>), typeof(ViewModel1), new PropertyMetadata(null));

The initial binding works because there is a property named Col, but it is not detected as a dependency property, so the binding is not automatically updated.

Upvotes: 7

Related Questions