這是我的示例代碼,爲什麼PropertyChangedEventHandler屬性爲null?
該列表與列表框綁定,該列表框應訂閱該事件。不應該嗎?爲什麼INotifyPropertyChanged的事件PropertyChangedEventHandler始終爲空?
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>
你是說列表框正在顯示,但你的事件仍然爲空? – Gabe 2011-05-04 15:03:09
@Gabe,列表顯示正常,但var h = this.PropertyChanged;爲空,爲什麼?我該如何提高事件 – 2011-05-04 15:40:37
因此,即使在列表顯示之後,「PropertyChanged」仍然爲空? – Gabe 2011-05-04 15:45:40