简体   繁体   English

Label ToolTip中的StringFormat

[英]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 (ie I only get the date without the string "Date: " - eg "1/1/2015 15:38") apparently because the ToolTip type is object. 但是这不起作用(即我只得到没有字符串“Date:”的日期 - 例如“1/1/2015 15:38”),显然是因为ToolTip类型是对象。 I've tried several remedies such as 1) putting the binding inside a TextBlock inside a tooltip inside a label.tooltip inside the label; 我已经尝试了几种补救措施,例如1)将绑定放在一个工具提示内的TextBp里面,标签里面的label.tooltip; 2) putting a TextBlock inside a label.tooltip with the binding (and several others); 2)使用绑定(以及其他几个)将TextBlock放在label.tooltip中; 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) (我不介意使用转换器,只要1)没有涉及外部库2)后面的代码中没有任何内容 - 我希望所有显示代码都在XAML中)

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 . 问题是ToolTip被键入为object ,绑定的StringFormat部分仅在dependency属性为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. textblock将输出正确的东西( Date: .... ),而标签只会在DateTime上调用ToString()


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: 或者,您可以将工具提示绑定到viewmodel上的属性,该属性为您执行格式设置:

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

And then: 接着:

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

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 . 我已经测试了它并且它可以工作并打印“Date:”字符串, 但只有日期 Maybe the problem is that your svm.date is not a date. 也许问题是你的svm.date不是约会对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM