Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF binding with StringFormat doesn't work on ToolTips

Tags:

binding

wpf

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?

like image 825
huseyint Avatar asked Oct 13 '08 09:10

huseyint


3 Answers

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.

like image 195
Matt Hamilton Avatar answered Oct 15 '22 11:10

Matt Hamilton


It could be a bug. When you use short syntax for tooltip:

<TextBox ToolTip="{Binding WhatEverYouWant StringFormat='It is: \{0\}'}" />

StringFormat is ignore but when you use expanded syntax:

<TextBox Text="text">
   <TextBox.ToolTip>
      <TextBlock Text="{Binding WhatEverYouWant StringFormat='It is: \{0\}'}"/>
   </TextBox.ToolTip>
</TextBox>

It works as expected.

like image 30
MuiBienCarlota Avatar answered Oct 15 '22 11:10

MuiBienCarlota


As Matt said ToolTip can contain anything inside so for your you could bind a TextBox.Text inside your ToolTip.

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

Even you can Stack a grid inside the ToolTip and layout your text if you want.

like image 5
Lucas Locatelli Avatar answered Oct 15 '22 13:10

Lucas Locatelli