【WPF】在Style中設定ToolTip的問題

來源:互聯網
上載者:User

更新:在網上找到更正規的解決方案
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還是一個未解之謎。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.