Label ToolTip中的StringFormat

时间:2015-10-01 13:06:07

标签: wpf xaml binding

我正在尝试将标签内的工具提示设置为绑定:

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

然而这不起作用(即我只得到没有字符串“Date:”的日期 - 例如“1/1/2015 15:38”),显然是因为ToolTip类型是对象。 我已经尝试了几种补救措施,例如1)将绑定放在一个工具提示内的TextBp里面,标签里面的label.tooltip; 2)使用绑定(以及其他几个)将TextBlock放在label.tooltip中; 所有这些都不起作用。

有没有简单的方法来实现我想要的? (我不介意使用转换器,只要1)没有涉及外部库2)后面的代码中没有任何内容 - 我希望所有的显示代码都在XAML中)

2 个答案:

答案 0 :(得分:2)

问题是ToolTip的类型为object,而绑定的StringFormat部分仅在dependency property is of type string时使用。

很容易重现:

<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>

文本块将输出正确的内容(Date: ....),而标签只会在DateTime上调用ToString()

要解决您的问题,只需稍微详细地定义工具提示:

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

或者您可以将工具提示绑定到viewmodel上的属性,该属性为您执行格式设置:

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

然后:

<Label ToolTip="{Binding MyTooltipString}" />

答案 1 :(得分:1)

试试这个:

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

<强>编辑&gt;&GT;&GT;&GT;

我测试了它并且它可以工作并打印“Date:”字符串,但只有日期。也许问题是你的svm.date不是约会。

相关问题