TomM
TomM

Reputation: 385

StringFormat inside a Label ToolTip

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)

Upvotes: 1

Views: 922

Answers (2)

Isak Savo
Isak Savo

Reputation: 35884

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}" />

Upvotes: 3

Jose
Jose

Reputation: 1897

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.

Upvotes: 1

Related Questions