[英]INotifyPropertyChanged PropertyChangedEventHandler event is always null
[英]Why INotifyPropertyChanged's event PropertyChangedEventHandler is always null?
這是我的示例代碼,為什么 PropertyChangedEventHandler 屬性是 null?
該列表綁定到應該訂閱該事件的列表框。 不應該嗎?
public class Data<T> : INotifyPropertyChanged where T : class
{
T _data;
public T MyData
{
get { return _data; }
set
{
_data = value;
this.OnPropertyChanged("MyData");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string property)
{
var h = this.PropertyChanged;
if (h != null)
{
h(this, new PropertyChangedEventArgs(property));
}
}
}
class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
public Window1()
{
InitializeComponent();
List<Data<Person>> list = new List<Data<Person>>();
list.Add(new Data<Person> { MyData = new Person { Name = "Sam", Age = 21 } });
list.Add(new Data<Person> { MyData = new Person { Name = "Tom", Age = 33 } });
this.DataContext = list;
}
<Grid>
<ListBox Name="listbox1"
ItemsSource="{Binding}"
Style="{DynamicResource lStyle}" >
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" >
<Label Width="100" Content="{Binding Path=MyData.Name}"></Label>
<Label Width="100" Content="{Binding Path=MyData.Age}"></Label>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
可能是因為 ListBox 還沒有機會渲染並開始監聽更改事件。
當我在 listbox1_MouseLeftButtonDown 內部更改期間測試以下PropertyChanged
不是listbox1_MouseLeftButtonDown
時。
Data<Person> p;
public MainWindow()
{
InitializeComponent();
List<Data<Person>> list = new List<Data<Person>>();
this.p = new Data<Person> { MyData = new Person { Name = "Sam", Age = 21 } };
list.Add(this.p);
this.DataContext = list;
}
private void listbox1_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
p.DataContext = null;
}
在您提供的代碼中,將訂閱 PropertyChanged 事件處理程序。 為什么你認為情況並非如此?
像這樣的更改將正確更新列表框:
List<Data<Person>> list = DataContext as List<Data<Person>>;
list[0].MyData = new Person() { Name = "Bob", Age = 12 };
請記住,您的數據 class 不支持單個屬性的屬性通知,因此以下更改不會更新列表框。
List<Data<Person>> list = DataContext as List<Data<Person>>;
list[0].MyData.Name = "Bob";
list[0].MyData.Age = 12;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.