今天在群裡有人問到:
“怎樣設置 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還是一個未解之謎。