![](/img/trans.png)
[英]ObservableCollection not updating through INotifyPropertyChanged
[英]TreeViewItem not updating with bound ItemsSource, ObservableCollection, and INotifyPropertyChanged
我知道這個問題已經問了很多,但是即使嘗試了所有不同的答案,我仍然無法解決這個問題。 我試圖綁定的對象正在后面的代碼中正確更新,因此,唯一的不起作用的是更改ItemsSource時TreeViewItem的子級更新。
看來我的所有設置都正確,但也許我在將事情捆綁在一起方面有些問題,這使它無法正常工作。 我正在Windows 7中的VS 2015中使用C#.NET 4.5 WPF項目。我綁定到靜態類的靜態屬性,該靜態屬性僅對TreeViewItem的ItemsSource具有get方法並設置DisplayMemberPath。
XAML:
<!-- Menu tree -->
<TreeView Grid.Column="0"
x:Name="menutree"
Background="Transparent"
BorderThickness="0">
<!-- Profiles TVI -->
<TreeViewItem Header="{x:Static loc:Resources.profiles}"
IsExpanded="True">
<!-- Color profile TVI -->
<TreeViewItem x:Name="colorTvi"
Header="{x:Static loc:Resources.colorProfiles}"
MouseRightButtonDown="colorTvi_MouseRightButtonDown"
DisplayMemberPath="Name"
ItemsSource="{Binding Source={x:Static local:Shared.ColorProfiles}, Mode=OneWay}" />
<TreeViewItem ...
類/屬性綁定到:
public static class Shared
{
#region Getter / Setter
// Notify property changed
public static NotifyChanged Notify { get; set; } = new NotifyChanged();
// All profiles that have been created
public static List<Profile> Profiles
{
get { return _Profiles; }
set
{
// Set profile
_Profiles = value;
Notify.OnPropertyChanged(nameof(Profiles));
Notify.OnPropertyChanged(nameof(ColorProfiles));
}
}
private static List<Profile> _Profiles = new List<Profile>();
// Color profiles
public static ObservableCollection<ColorProfile> ColorProfiles
{
get
{
return new ObservableCollection<ColorProfile>(
Profiles?.Where(m => m.GetType() == typeof(ColorProfile))?.Cast<ColorProfile>()?.ToList() ??
new List<ColorProfile>());
}
}
#endregion
}
NotifyChanged類:
// Property changed class
public class NotifyChanged : INotifyPropertyChanged
{
// Property changed event
public event PropertyChangedEventHandler PropertyChanged;
// Notify property changed
public void OnPropertyChanged(string name)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
}
我想讓它工作而不必在后面的代碼中調用Refresh()。 我已經嘗試直接綁定到Shared.Profiles,但這無濟於事。 ColorProfile是從Profile繼承的基類。
希望我缺少一些愚蠢,簡單的東西。 先謝謝您的幫助。
更新:
經過進一步檢查,實際上看起來ItemsSource甚至沒有更新。 在調試期間,我可以在控件的屬性瀏覽器中看到ItemsSource綁定到ObservableCollection,但是ItemsSource並未反映對列表所做的更改。 如果我手動綁定后面的代碼,那么它將起作用。
通知本身就是一個大喊PropertyChanged的事件。
沒有人綁定到通知,因此也沒有人在更新。
需要實現INotifyPropertyChanged或從NotifyChanged繼承的人是共享的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.