开发者

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 firs开发者_开发知识库tname; }
    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);
  }
}


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>


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]


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


You can use multi-binding (without a converter) to invoke the ToString() method when one or more properties change.

<StackPanel>
  <TextBlock>
    <TextBlock.Text>
      <MultiBinding StringFormat="{}{0}">
        <Binding Path="" />
        <Binding Path="Firstname" />
        <Binding Path="Surname" />
      </MultiBinding>
    </TextBlock.Text>
  </TextBlock>
</StackPanel>


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

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜