为什么INotifyPropertyChanged的事件PropertyChangedEventHandler总是为空?

时间:2011-05-04 14:29:01

标签: c# wpf inotifypropertychanged

这是我的示例代码,为什么PropertyChangedEventHandler属性为null? 该列表受限于Listbox,它应该订阅该事件。不应该吗?

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>

2 个答案:

答案 0 :(得分:1)

可能是因为ListBox还没有机会渲染并开始侦听变更事件。

当我在PropertyChanged内进行更改时,我测试了以下listbox1_MouseLeftButtonDown并非null。

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;
}

答案 1 :(得分:0)

在您提供的代码中,将订阅PropertyChanged事件处理程序。为什么你认为情况并非如此?

这样的更改会正确更新列表框:

List<Data<Person>> list = DataContext as List<Data<Person>>; 
list[0].MyData = new Person() { Name = "Bob", Age = 12 };

请记住,您的Data类不支持对各个属性的属性通知, 因此以下更改不会更新列表框。

List<Data<Person>> list = DataContext as List<Data<Person>>; 
list[0].MyData.Name = "Bob"; 
list[0].MyData.Age = 12;