tags:

views:

3879

answers:

2

The following code has a simple binding which binds the Text of the TextBlock named MyTextBlock to TextBox's Text and ToolTip property using the exact same Binding notation:

<StackPanel>
    <TextBlock x:Name="MyTextBlock">Foo Bar</TextBlock>
    <TextBox    Text="{Binding ElementName=MyTextBlock, Path=Text, StringFormat='It is: \{0\}'}"
             ToolTip="{Binding ElementName=MyTextBlock, Path=Text, StringFormat='It is: \{0\}'}" />
</StackPanel>

The binding also uses the StringFormat property introduced with .NET 3.5 SP1 which is working fine for the above Text property but seems to be broken for the ToolTip. The expected result is "It is: Foo Bar" but when you hover over the TextBox, the ToolTip shows only the binding value, not the string formatted value. Any ideas?

+19  A: 

ToolTips in WPF can contain anything, not just text, so they provide a ContentStringFormat property for the times you just want text. You'll need to use the expanded syntax as far as I know:

<TextBox ...>
  <TextBox.ToolTip>
    <ToolTip 
      Content="{Binding ElementName=myTextBlock,Path=Text}"
      ContentStringFormat="{}It is: {0}"
      />
  </TextBox.ToolTip>
</TextBox>

I'm not 100% sure about the validity of binding using the ElementName syntax from a nested property like that, but the ContentStringFormat property is what you're looking for.

Matt Hamilton
I see, I thought ToolTip is just a plain string as in Windows Forms. And yes, ElementName syntax in this case can not access the outer element.
huseyint
Note that the {} is required only when you place the {0} at the beginning of the string, so you need it to distinguish from the other xaml markups.
Shimmy
Mind = blown. I just hit this and was like "waaaat?"
Will
A: 

The following is a wordy solution but it works.

<StackPanel>
  <TextBox Text="{Binding Path=., StringFormat='The answer is: {0}'}">
    <TextBox.DataContext>
      <sys:Int32>42</sys:Int32>
    </TextBox.DataContext>
    <TextBox.ToolTip>
      <ToolTip Content="{Binding}" ContentStringFormat="{}The answer is: {0}" />
    </TextBox.ToolTip>
  </TextBox>
</StackPanel>

I would prefer a much simpler syntax, something like the one in my original question.

huseyint
Why did you mark your own question as answer whilst there is a better answer that was answered 3 hours before you???
Shimmy
@Shimmy: "better" is in the eye of the beholder, and it's alright to mark your own question the accepted answer
Andomar
@Shimmy Even worse, his answer includes a '42' joke.
Will
@Andomar, better is what folks decide with their votes, also particullary here, it's almost just the same answer. making ppl answer your questions then copy their answers and gain reputation for it is a completely wrong atitude.
Shimmy
@Shimmy: I don't think you gain reputation for marking your own answer as accepted
Andomar