Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF Binding - Notify Change to ToString value

I have a textblock that is bound to an object. This object I have overridden ToString to return a combination of 2 other properties. How can I notify that the ToString value has been changed when one of the property values is updated?

Unfortunately I cannot change the binding to the ToString value as this is within a 3rd party control so really need to be able to notify directly.

Hopefully the class definition below will clarify what I mean:

public class Person : INotifyPropertyChanged
{
  private string firstname;
  public string Firstname
  {
    get { return firstname; }
    set
    {
      firstname = value;
      OnPropertyChanged("Firstname");
    }
  }

  private string surname;
  public string Surname
  {
    get { return surname; }
    set
    {
      surname = value;
      OnPropertyChanged("Surname");
    }
  }

  public override string ToString()
  {
    return string.Format("{0}, {1}", surname, firstname);
  }
}
like image 488
David Ward Avatar asked Feb 19 '10 12:02

David Ward


2 Answers

I assume when you say the control is "binding" to ToString() that your object is being used as Content on ContentControl somewhere inside the inaccessible code which by default creates a TextBlock that displays the ToString value (if you're not sure you can find out with Snoop). If you create a global typed DataTemplate for your Person type in the control's Resources you can use that to display a different property, like a new FullName property:

<ThirdPartyControl.Resources>
  <DataTemplate DataType="{x:Type data:Person}">
    <TextBlock Text="{Binding FullName}"/>
  </DataTemplate>
</ThirdPartyControl.Resources>
like image 52
John Bowen Avatar answered Oct 19 '22 11:10

John Bowen


If you don't want to add a specialized property for the full name, you should be able to use StringFormat in you binding. See the MultiBinding example in this blog post. [Requires .NET 3.5 SP1]

like image 26
Mikael Sundberg Avatar answered Oct 19 '22 11:10

Mikael Sundberg