.NET 3.5 SP1 StringFormat 绑定属性的奇怪之处 (吐槽)






3.67/5 (2投票s)
这是一篇关于 .NET 3.5 SP1 StringFormat 绑定属性的吐槽。
.NET 3.5 SP1 包含一些很棒的功能,其中之一是新的 StringFormat
绑定属性,它非常有用。这意味着你不再需要编写 ValueConverters
来为绑定创建格式化的值。我非常喜欢这个 WPF 的小改进。
唯一的问题是,我前几天需要在 ToolTip 中使用它,但它就是不起作用。考虑以下 XAML,我正在使用 3 个带有自定义绑定的 TextBox
。
- 第一个使用
StringFormat
绑定属性来创建对TextBox.Text
属性的绑定。一切正常,正如预期的那样。 - 第二个使用自定义
ToolTip
用于TextBox
,只是为了证明我们可以这样做。一切正常,正如预期的那样。 - 第三个也使用自定义
ToolTip
用于TextBox
,使用与编号 1 中相同的绑定,但我们使用ToolTip
属性而不是Text
。而且,它根本没有使用StringFormat
属性中的string
。它确实使用了一些值,但似乎只使用了原始值,放弃了Format String
的其余部分。非常奇怪。
现在,我对此没有答案,除了说如果你想要基于绑定值的格式化 ToolTip
,你可能需要使用 ValueConverters
。我只是觉得这个小问题可能对阅读这篇文章的人来说会很有趣。基本上,这是一篇我决定记录的吐槽。
这里是支持我的观点的代码和屏幕截图。
1: <Window x:Class="StringFormatBinding.Window1"
2: xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
3: xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
4: Title="StringFormat Binding Weirdness" Height="300" Width="300"
5: SizeToContent="WidthAndHeight"
6: WindowStartupLocation="CenterScreen">
7: <StackPanel Orientation="Vertical">
8:
9: <!– This binding using StringFormat works just fine–>
10: <StackPanel Orientation="Horizontal" Margin="5"
11: Background="WhiteSmoke">
12: <Label Content="This Custom Binding Works Fine"/>
13: <TextBox x:Name="txt1" Width="180" Height="25"
14: Text="{Binding Path=Width,
15: ElementName=txt1, Mode=Default,
16: StringFormat=’Element is {0} Wide’}"/>
17: </StackPanel>
18:
19: <!– Are here is a custom tooltip for a TextBox–>
20: <StackPanel Orientation="Horizontal" Margin="5"
21: Background="WhiteSmoke">
22: <Label Content="This Custom ToolTip is ok"/>
23: <TextBox x:Name="txt2" Width="180" Height="25"
24: ToolTip="CUSTOM TOOL TIP"/>
25: </StackPanel>
26:
27: <!– So why doesnt the binding using StringFormat
28: work for ToolTip –>
29: <StackPanel Orientation="Horizontal" Margin="5"
30: Background="WhiteSmoke">
31: <Label Content="This Custom ToolTip is ok"/>
32: <TextBox x:Name="txt3" Width="180" Height="25"
33: ToolTip="{Binding Path=Width,
34: ElementName=txt3, Mode=Default,
35: StringFormat=’Tooltip : Element is {0} Wide’}"/>
36: </StackPanel>
37:
38: </StackPanel>
39: </Window>
这里是关于我所说的内容的屏幕截图。
顶部的 TextBox
正常工作,第二个也正常工作。
但是这个小家伙,就是不行。 哼!
我假设这是 WPF 中的一个问题,将在后续版本中得到解决。