1

I'm trying to set a tooltip inside a label to a binding:

<Label Content="x"
 ToolTip="{Binding ElementName=_this, Path=date, StringFormat=Date: {0:G}}" />

However this doesn't work (i.e. I only get the date without the string "Date: " - e.g. "1/1/2015 15:38") apparently because the ToolTip type is object. I've tried several remedies such as 1) putting the binding inside a TextBlock inside a tooltip inside a label.tooltip inside the label; 2) putting a TextBlock inside a label.tooltip with the binding (and several others); All of which do not work.

Is there any simple way of achieving what I want? (I don't mind using converters as long as 1) no external library is involved 2) there is nothing in the code behind - I want all the display code to be in XAML)

TomM
  • 375
  • 3
  • 16

2 Answers2

3

The problem is that ToolTip is typed to be object and the StringFormat part of a binding is only used when the dependency property is of type string.

It's easy to reproduce:

<StackPanel>
    <TextBlock Text="{Binding Source={x:Static system:DateTime.Now}, StringFormat=Date: {0:g}}" />
    <Label Content="{Binding Source={x:Static system:DateTime.Now}, StringFormat=Date: {0:g}}" />
</StackPanel>

The textblock will output the correct thing (Date: ....) while the label will just call ToString() on the DateTime.


To solve your problem, simply define the tooltip in the slightly more verbose way:

<Label Content="x">
    <Label.ToolTip>
        <TextBlock Text="{Binding Source={x:Static system:DateTime.Now}, StringFormat=Date: {0:g}}" />
    </Label.ToolTip>
</Label>

Or you can bind the tooltip to a property on your viewmodel which does the formatting for you:

public string MyTooltipString { get { return String.Format("Date: {0:g}", theDate); } }

And then:

<Label ToolTip="{Binding MyTooltipString}" />
Community
  • 1
  • 1
Isak Savo
  • 34,957
  • 11
  • 60
  • 92
  • I tried this: `` and the tooltip is empty. – TomM Oct 01 '15 at 14:45
  • As for the other suggestion - I would prefer my code to be in XAML so that it's not hidden behind in the code (since it is an integral part of the display). If there is no other option then I will put the code in the codebehind. – TomM Oct 01 '15 at 14:50
1

Try this:

<Label Content="x"
ToolTip="{Binding ElementName=_this, Path=svm.date, StringFormat=Date: {0:G} }" />

EDIT>>>>

I've tested it and it works and prints the "Date:" string, but only with dates. Maybe the problem is that your svm.date is not a date.

Jose
  • 1,857
  • 1
  • 16
  • 34