You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让WPF中Border元素的Hover事件在鼠标进入其整个区域时触发?

修复Border整个区域触发悬停效果的问题

问题根源是Border默认未设置Background:WPF中元素的Background为null时,空白区域不会响应鼠标命中测试,导致IsMouseOver仅在子元素(文本、图标)区域触发。

解决方法

给Border添加透明背景,让整个区域都能捕获鼠标事件:

修改后的完整代码

<Border CornerRadius="5"
        Width="190"
        Height="40"
        Margin="0,5,0,0"
        Background="Transparent"> <!-- 新增透明背景 -->
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="35" />
        </Grid.ColumnDefinitions>
        <TextBlock Grid.Column="0"
                   Text="تجهیزات"
                   FlowDirection="RightToLeft"
                   VerticalAlignment="Center"
                   Margin="0,0,10,0">
            <TextBlock.Style>
                <Style>
                    <Setter Property="TextBlock.FontFamily" Value="{StaticResource Vazir}"/>
                    <Setter Property="TextBlock.FontSize" Value="14"/>
                    <Setter Property="TextBlock.Foreground" Value="White"/>
                </Style>
            </TextBlock.Style>
        </TextBlock>
        <Viewbox Grid.Column="1" Width="25" Height="25" Stretch="Uniform" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
            <Canvas Height="512" Width="512">
                <Path Fill="White" Data="M135.2 117.4L109.1 192l293.8 0-26.1-74.6C372.3 104.6 360.2 96 346.6 96L165.4 96c-13.6 0-25.7 8.6-30.2 21.4zM39.6 196.8L74.8 96.3C88.3 57.8 124.6 32 165.4 32l181.2 0c40.8 0 77.1 25.8 90.6 64.3l35.2 100.5c23.2 9.6 39.6 32.5 39.6 59.2l0 144 0 48c0 17.7-14.3 32-32 32l-32 0c-17.7 0-32-14.3-32-32l0-48L96 400l0 48c0 17.7-14.3 32-32 32l-32 0c-17.7 0-32-14.3-32-32l0-48L0 256c0-26.7 16.4-49.6 39.6-59.2zM128 288a32 32 0 1 0 -64 0 32 32 0 1 0 64 0zm288 32a32 32 0 1 0 0-64 32 32 0 1 0 0 64z" />
            </Canvas>
        </Viewbox>
    </Grid>
    <Border.Style>
        <Style TargetType="{x:Type Border}">
            <Style.Triggers>
                <Trigger Property="IsMouseOver" Value="True" >
                    <Setter Property="Background" Value="White"  />
                </Trigger>
            </Style.Triggers>
        </Style>
    </Border.Style>
</Border>

补充说明

  • 设置Background="Transparent"不会改变元素原有视觉效果,但会让Border的整个矩形区域参与鼠标命中测试。
  • 若需要保留初始背景,也可设置为与父容器背景一致的颜色,同样能实现全区域悬停触发。

内容的提问来源于stack exchange,提问作者Alex Wright

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 15:00:08