將 RadioButton 放置於 GroupBox.Header 內容中時,滑鼠點擊或懸停於 RadioButton 某些空白區域完全無反應。本文透過 Visual Tree 分析,精確定位問題根因於 GroupBox 預設樣式中一個隱形 Border 元素覆蓋在 Header 區域上方,攔截滑鼠事件。
<GroupBox>
<GroupBox.Header>
<RadioButton x:Name="targetRadioButton" Content="HeaderRadioButton" GroupName="header"/>
</GroupBox.Header>
<GroupBox.Content>
<StackPanel>
<RadioButton Content="CommonRadioButton"/>
<RadioButton Content="CommonRadioButton"/>
</StackPanel>
</GroupBox.Content>
</GroupBox>
使用 XAML Pad 或 Visual Studio Live Visual Tree 檢視,發現 targetRadioButton 的 Visual Tree 中藏有一個 Border:
Background=Transparent、BorderBrush=White、BorderThickness=10、CornerRadius=4此 Border 來自 GroupBox 預設 ControlTemplate 中的 Header 區域裝飾邊框,設計上為了視覺效果,卻未將 IsHitTestVisible="False"。
Background 改為紅色、BorderBrush 改為綠色,立即可見覆蓋區域<Style TargetType="GroupBox">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="GroupBox">
<!-- 關鍵:Header 區域的 Border 設定 IsHitTestVisible="False" -->
<Border x:Name="headerBorder" IsHitTestVisible="False" ...>
<ContentPresenter ContentSource="Header"/>
</Border>
<!-- Content 區域保持正常 -->
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
public static class GroupBoxHeaderFix {
public static void Apply(GroupBox groupBox) {
groupBox.Loaded += (s, e) => {
var headerBorder = FindVisualChild<Border>(groupBox, "headerBorder"); // 需知 Template 中名稱
if (headerBorder != null) headerBorder.IsHitTestVisible = false;
};
}
}
將 RadioButton 移至 Content 區域,或使用 HeaderTemplate 僅放置非互動元素 (TextBlock、Image)。
WPF 中類似「看不見的元素攔截事件」問題常見於:
診斷金鑰:遇到 UI 區域無故失效,優先檢查 Visual Tree 尋找透明但 HitTestVisible 的元素。