3

ObservableCollection が (新しいものに) 置き換えられ、変更されていない (アイテムが追加または削除された) 場合に、ListView が更新されない理由がわかりません。ビュー モデルに DependencyObject を使用しており、コレクションが置換されると SetValue が呼び出されるため、プロパティ通知のすべての要件を尊重しました。

ビュー モデルの Col プロパティにバインドされた WPF ListView があります。

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));

}

XAML は次のようになります。

<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>

したがって、このコードでは、最初の ObservableCollection を置き換えなければ、すべて正常に動作します。しかし、ボタンをクリックすると。リストを次のように置き換えます。

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

        }

ビュー モデルの PropertyChanged メソッドが Col に対して呼び出されますが、ListView はそのコンテンツを更新していません。

同じ ObservableCollection 参照を保存する必要がありますか? なぜ ?

4

1 に答える 1