![](/img/trans.png)
[英]ListView not updating when the bound ObservableCollection changes
[英]ListView not updating when ObservableCollection is replaced
我無法理解為什么在替換ObservableCollection(使用新的)並且未更改(添加或刪除的項目)時不會刷新ListView。 我尊重屬性通知的所有要求,因為我正在為我的視圖模型使用DependencyObject,並且在替換集合時調用SetValue。
我有一個WPF ListView綁定到我的視圖模型的Col屬性:
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" });
}
對於Col調用視圖模型上的PropertyChanged方法,但ListView不更新其內容。
我是否需要保存相同的ObservableCollection引用? 為什么?
這是因為您的依賴項屬性注冊不正確。 傳遞給Register
方法的屬性名稱應為“Col”,而不是“ColProperty”:
public static readonly DependencyProperty ColProperty =
DependencyProperty.Register("Col", typeof(ObservableCollection<string>), typeof(ViewModel1), new PropertyMetadata(null));
初始綁定有效,因為有一個名為Col
的屬性,但它沒有被檢測為依賴屬性,因此綁定不會自動更新。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.