在下面的代碼示例中,Person 型別的屬性與 ObesrvableCollection 型別的屬性發生了不同的行為。在這兩種情況下,TextBox 都必須編輯 Person.Name 欄位。對于這兩種情況,TextBlock 都用于在欄位上顯示更新的值。在 ObservableCollection 的情況下,TextBlock 在 TextBox 上的編輯完成后,在“淡出焦點”事件后更新。在普通屬性的情況下,當淡出焦點上的 TextBox 中的值發生更改時,TextBlock 不會更新。有什么不同?在 ObservableColletion 欄位值更新的情況下,幕后發生了什么?
Xaml 視圖:
<UserControl ...>
<StackPanel>
<ListBox ItemsSource="{Binding People}" Height="100">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBox Text="{Binding Name}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<TextBlock Text="{Binding People[0].Name}"/>
<TextBox Text="{Binding Mike.Name}"/>
<TextBlock Text="{Binding Mike.Name}"/>
</StackPanel>
</UserControl>
視圖模型:
class MainViewModel : BindableBase
{
private Person _mike;
public Person Mike
{
get { return _mike; }
set { SetProperty(ref _mike, value); }
}
public ObservableCollection<Person> People { get; set; } = new ObservableCollection<Person>();
public MainViewModel()
{
People.Add(new Person("Lisa"));
People.Add(new Person("Chris"));
People.Add(new Person("Orlando"));
}
}
人物類:
class Person
{
public string Name { get; set; }
public Person(string name)
{
Name = name;
}
}
編輯:
我在我的代碼中發現了這個問題。這是屬性 Mike 從未被分配過一個型別為 person 的值。因此它不會在 TextBlock 中更新。但我的問題仍然存在:為什么即使 person 的 Name 屬性沒有實作 INotifyChanged 機制,TextBlock 也會更新?
class MainViewModel : BindableBase
{
private Person _mike = new Person("Mike");
public Person Mike
{
get { return _mike; }
set { SetProperty(ref _mike, value); }
}
public ObservableCollection<Person> People { get; set; } = new ObservableCollection<Person>();
public MainViewModel()
{
People.Add(new Person("Lisa"));
People.Add(new Person("Chris"));
People.Add(new Person("Orlando"));
}
}
uj5u.com熱心網友回復:
Person 需要實作BindableBase(假設實作了INotifyPropertyChanged),您需要Name像這樣設定屬性:
private string _name;
public string Name
{
get { return _name; }
set { SetProperty(ref _name, value); }
}
的ObservableCollection目的是為了通知當一個專案被添加,移動或移除; 它不跟蹤專案的屬性。
uj5u.com熱心網友回復:
使用INotifyPropertyChanged:
class CarList : INotifyPropertyChanged
{
public string ModelNumber { get; set; }
private string modelName;
public string ModelName
{
get { return modelName; }
set
{
modelName = value;
OnPropertyChanged("ModelName");
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged([CallerMemberName] string pchange = "")
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(pchange));
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/329719.html
