Updating nested property

Sep 18, 2009 at 8:24 PM

I have a class, MyMainClass, with a member that is also a class, MyChildClass.  MyChildClass is accessed through a property named "ChildClass".  I have a WPF TextBlock that binds to a property of the ChildClass named "Name".  I use {binding = MyChildClass.Name}.  In my code I instantiate a MyMainClass object and set the DataContext of my <Grid> to it.  The TextBlock picks up the proper value of MyChildClass.Name.  This problem I having is trying to have the control update with a new value.  I tried using OnPropertyChanged(...("MyChildClass.Name")) and OnPropertyChanged(...("Name") but the TextBlock still won't update.  I then tried OnPropertyChanged(...("")) and this time it does update.  But I don't want all fields to update which from my understanding is what the empty string does.

I also tried PropertyChanged(this,e) and even PropertyChanged(this.MyChildClass) with the various property names with no luck.

Am I doing something wrong?


Sep 18, 2009 at 10:13 PM

My knowledge is that you will need your ItemsSource of datagrid bound to an observable collection which implements INotifyCollectionChanged which will upadate the grid items source.

More info http://msdn.microsoft.com/en-us/library/ms752347.aspx#binding_to_collections

Sep 19, 2009 at 1:05 AM

I am not actually using a grid, but the <Grid> container which defines a grid type of layout of children.  MyMainClass implements INotifyPropertyChanged (I think that is the name, I don't have the files with me right now).  MyChildClass is not however, but since it is able to work when I initially set the <Grid>'s DataContext and is does update when I use OnPropertyChanged(...("")) I would think it work in a nested fashion using "ChildClass.Name".  When I get a chance I will post sections of code to show what I am trying to do.


Sep 19, 2009 at 2:34 PM

I tried to put together some code from what I can remember:

public class MyChildClass
   public string Name { get... }

public class MyMainClass : INotifyPropertyChanged
   public ChildClass { get... }
   public event PropertyChangedEventHandler PropertyChanged;
   public void OnPropertyChanged(PropertyChangedEventArgs a_Args)
      if (PropertyChanged != null)
         PropertyChanged(this, a_Args);
   public void Foo()
      OnPropertyChanged(new PropertyChangedEventArgs("MyChildClass.Name"));

public MyTest : Window
   private MyMainClass mainClass = new MyMainClass();
   public void Init()
      mainClass.ChildClass = new MyChildClass();
      mainClass.ChildClass.Name = "James";
      MainArea.DataContext = mainClass;
   public void FooAction()
      mainClass.ChildClass.Name = "Richard";

<Window ...>
   <Grid name="MainArea">
   <TextBlock Text="{Binding Path=ChildClass.Name}"/>