DataBinding in WPF?

There’s a bunch of problems here.

The first and probably most significant one is that you’ve implemented Person.name as a field. Binding doesn’t work with fields. Person.name needs to be a property.

The next issue that you have is that if you want a control to be updated with the value of a property when that property changes, your class has to implement property-change notification. (Which is another reason that Person.name has to be a property.)

A third issue is that you’re using WinForms techniques in a WPF application. Data binding eliminates most of the use cases for the TextChanged event. (Not all: it can be useful when you’re developing custom controls.)

A fourth issue is there’s no need for value conversion, so no need to implement a value converter.

A Person class that implements property-changed notification correctly should look something like this:

public class Person : INotifyPropertyChanged
{
   public event PropertyChangedEventHandler PropertyChanged;

   private void OnPropertyChanged(string propertyName)
   {
      PropertyChangedEventHandler h = PropertyChanged;
      if (h != null)
      {
         h(this, new PropertyChangedEventArgs(propertyName));
      }
   }

   public Person() { }

   public Person(string name)
   {
      Name = name;
   }

   private string _Name = "I was created by the parameterless constructor";

   public string Name
   { 
      get { return _Name; }
      set
      {
         if (_Name == value)
         {
            return;
         }
         _Name = value;
         OnPropertyChanged("Name");
      }
   }
}

Once you’ve done this, if you create a Person object and bind any TextBox objects’ Text properties to its Name property, they’ll all be maintained in sync, e.g.:

<StackPanel>
   <StackPanel.DataContext>
      <local:Person Name="John Smith"/>
   </StackPanel.DataContext>
   <TextBox Text="{Binding Name, Mode=TwoWay}"/>
   <TextBox Text="{Binding Name, Mode=TwoWay}"/>
</StackPanel>

There’s much, much more to WPF data binding than this, but this should get you going down the right track.

Leave a Comment