views:

313

answers:

4

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);
  }
}
+1  A: 

you can add third read-only property, which returns ToString(), and call OnPropertyChanged with name of that property

Yurec
A: 

Do not bind to ToString(). Instead introduce a FullName property and raise OnPropertyChanged("FullName") in both your other property setters.

klausbyskov
This would make sense except (and I did leave this detail out in the original post which I will now edit) that the binding on the ToString value is within a 3rd party control which I cannot change
David Ward
+2  A: 

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]

Mikael Sundberg
A: 

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>
John Bowen