爲什麼上升INotifypPropertyChanged
爲List<T>
屬性不起作用?爲什麼通知列表<T>屬性不起作用
考慮這個MCVE:
public class NotifyPropertyChanged : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged([CallerMemberName] string property = "") =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property));
}
public class TextWrapper
{
public string Text { get; set; }
public override string ToString() => Text;
}
public class ViewModel : NotifyPropertyChanged
{
public List<string> List { get; } = new List<string>();
public TextWrapper Text { get; } = new TextWrapper();
public void AddToList(string text)
{
List.Add(text);
OnPropertyChanged(nameof(List));
}
public void ChangeText(string text)
{
Text.Text = text;
OnPropertyChanged(nameof(Text));
}
}
public partial class MainWindow : Window
{
readonly ViewModel _vm = new ViewModel();
public MainWindow()
{
InitializeComponent();
DataContext = _vm;
}
}
XAML:
<TextBlock Text="{Binding Text}" />
<ListBox ItemsSource="{Binding List}" />
調用_vm.ChangeText(...)
將正確地更新TextBlock
,同時呼籲_vm.AddToList(...)
不更新ListBox
(它會一直爲空)。爲什麼?
請注意:我知道ObservableCollection<T>
,我知道大約兩個可能的解決方法(添加二傳手到List
並將其設置爲例如null
先升後回或更換DataContext
/ItemsSource
)。我只是好奇什麼在屋頂下使List<T>
比TextWrapper
更特別。
附註 - 不確定是否可能導致問題,但List是保留名稱。嘗試改變它或用「@」作爲前綴,如「@ List」。 –
@KamilSolecki用某個類的名字命名一個屬性是完全合法的。還要注意''List'是一個_generic_類,所以它的名字從來就不是簡單的「List」,而是「List'1」等。 –