首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Silverlight 控件禁用時 ToolTipService 仍顯示的解決方法

     編輯:程式設計綜合問答

問題背景

在 Silverlight 應用中,當控件被置灰(IsEnabled="False")時,預設情況下滑鼠懸停不會觸發 ToolTipService 顯示提示。新手開發者常遇到需求:即使控件不可用,也要讓使用者看到提示說明(如「請先勾選上方選項」)。

解決方案

參考 CSDN 博客文章 Silverlight 中禁用控件仍顯示 ToolTip 的方法,核心思路是:

  1. 將控件的 IsHitTestVisible 設為 True(預設禁用時為 False),使其仍能接收滑鼠事件。
  2. 或使用附加屬性 ToolTipService.ShowOnDisabled(Silverlight 5+ 支援),直接在 XAML 中設定:
    <Button Content="禁用按鈕" IsEnabled="False" ToolTipService.ToolTip="這是提示" ToolTipService.ShowOnDisabled="True" />
  3. 若版本較舊,可自訂 Style,將 ControlTemplate 中的 Disabled 狀態視覺狀態移除或調整,使 ToolTip 仍能彈出。

完整範例

<UserControl x:Class="SilverlightApp.MainPage"
    xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml">
    <StackPanel>
        <!-- Silverlight 5 以上直接使用 ShowOnDisabled -->
        <Button Content="無法點擊但有提示" IsEnabled="False" 
                ToolTipService.ToolTip="功能暫未開放,敬請期待" 
                ToolTipService.ShowOnDisabled="True" />
        
        <!-- 兼容舊版:用附加行為或自訂模板 -->
        <Button Content="舊版兼容" IsEnabled="False" 
                ToolTipService.ToolTip="請先登入" 
                IsHitTestVisible="True" />
    </StackPanel>
</UserControl>

注意事項

  • 設定 IsHitTestVisible="True" 會讓禁用控件仍能接收點擊事件,需在事件處理中自行判斷 IsEnabled 並忽略。
  • 建議升級至 Silverlight 5 並使用 ShowOnDisabled,最簡潔且符合預期行為。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved