您的位置:首页 > 其它

【WPF】在Style中设置ToolTip的问题

2009-01-14 15:17 288 查看
更新:在网上找到更正规的解决方案

http://thewpfblog.com/?p=61

今天在群里有人问到:

“怎样设置 TextBlock.ToolTip 的width,使得过长的字符串自动换行”

其实ToolTip是一个object,我们可以在其中放置任何东西,所以要解决这个问题,其实很简单,只需要写如下的xaml代码:

<TextBlock>

<TextBlock.ToolTip>

<TextBlock Text="xxxxxx" TextWrapping="Wrap"/>

</TextBlock.ToolTip>

</TextBlock>

但问题不在这儿,很显然,我们觉得每次写ToolTip都要这么写太麻烦了,想放到Style中去,比如:

<Style TargetType="TextBlock">

<Setter Property="ToolTipService.ToolTip">

<Setter.Value>

<TextBlock

Text="// 通过绑定等方式从某地方获取文本"

TextWrapping="Wrap"

Width="70" />

</Setter.Value>

</Setter>

</Style>

看上去这段代码没有任何问题,但编辑器却报告了一个异常:

无法向“System.Object”类型的对象添加“System.Windows.Controls.TextBlock”类型的内容。

Faint!

无奈,只能换个路子走,最后的代码如下:

<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

<Page.Resources>

<!-- Test -->

<TextBlock x:Key="ToolTipTemplate"

Text="Test Test Test Test Test Test Test Test Test Test Test Test"

TextWrapping="Wrap"

Width="70" />

<!-- 以下代码会报出异常 -->

<!-- 无法向“System.Object”类型的对象添加“System.Windows.Controls.TextBlock”类型的内容。 -->

<!--

<Style TargetType="TextBlock">

<Setter Property="ToolTipService.ToolTip">

<Setter.Value>

<TextBlock

Text="Test Test Test Test Test Test Test Test Test Test Test Test"

TextWrapping="Wrap"

Width="70" />

</Setter.Value>

</Setter>

</Style>

-->

<Style TargetType="TextBlock">

<Setter Property="ToolTipService.ToolTip" Value="{StaticResource ToolTipTemplate}" />

</Style>

</Page.Resources>

<Grid>

<TextBlock Text="xxx" Width="70" Height="26"/>

</Grid>

</Page>

OK,大功告成。注意红字部分,绕了个弯子。可以直接复制粘贴到XamlPad中查看。

但至于为什么不能直接在Setter.Value中放置TextBlock还是一个未解之谜。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: