簡體   English   中英

在 wpf 中設置子元素的邊距時,IsMouseOver 屬性不起作用

[英]IsMouseOver property is not working when margin of child element is set in wpf

最近在做一個wpf的聊天應用。 當鼠標懸停在邊框上時,我想更改邊框畫筆顏色。 但是,由於設置了邊距或填充,我的代碼不起作用。

示例代碼如下:

主窗口.xaml

<Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp1"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <TextBlock Text="Test" Name="testBlock"/>

        <Border Name="test" BorderThickness="1" Width="300" Height="200">

            <TextBlock Text="Test1" Margin="30"/>


            <Border.Style>
                <Style TargetType="Border">
                    <Style.Triggers>
                        <Trigger Property="IsMouseOver" Value="True">
                            <Setter Property="BorderBrush" Value="Red"/>
                        </Trigger>
                        <Trigger Property="IsMouseOver" Value="False">
                            <Setter Property="BorderBrush" Value="Yellow"/>
                        </Trigger>
                    </Style.Triggers>
                </Style>
            </Border.Style>
        </Border>
    </Grid>
</Window>

主窗口.xaml.cs

namespace WpfApp1
{
    public partial class MainWindow : Window
    {


        public MainWindow()
        {
            InitializeComponent();
        }
    }
}

在此處輸入圖片說明

我想在鼠標懸停在邊框上時更改邊框畫筆。 如何讓工作順利?

鼠標懸停事件的工作原理是檢測鼠標是否在控件的渲染像素上。 這樣做的好處是,例如,如果您制作一個帶邊框的圓形按鈕,您將只能在圓形部分中單擊它,而不能在圓形部分之外單擊它。 這是因為邊框外的顏色為“空”。 通過主動將其設置為透明,它將被渲染,從而能夠觸發鼠標懸停事件。

這將起作用:

        <Border Name="test" BorderThickness="1" Width="300" Height="200" Background="Transparent">

            <TextBlock Text="Test1" Margin="30"/>


            <Border.Style>
                <Style TargetType="Border">
                    <Style.Triggers>
                        <Trigger Property="IsMouseOver" Value="True">
                            <Setter Property="BorderBrush" Value="Red"/>
                        </Trigger>
                        <Trigger Property="IsMouseOver" Value="False">
                            <Setter Property="BorderBrush" Value="Yellow"/>
                        </Trigger>
                    </Style.Triggers>
                </Style>
            </Border.Style>
        </Border>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM