开发者

Why INotifyPropertyChanged's event PropertyChangedEventHandler is always null?

This is my sample code, why PropertyChangedEventHandler property is null?

the list is bounded to Listbox which should subscribe to the event. Shouldn't开发者_Python百科 it?

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>


Probably because the ListBox hasn't had a chance to render and start listening for change events yet.

When I tested the following PropertyChanged was not null during the change inside 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;
}


In your provided code, the PropertyChanged event handler will be subscribed to. Why do you think that is not the case?

Changes like this will update the listbox correctly:

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

Remember that your Data class don't support property notify on individual properties, so the following changes will not update the listbox.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜