仅当鼠标指针直接位于元素上方时,如何在 XAML 中显示工具提示

How do you show a tooltip in XAML only when the mouse pointer is directly over the element

我有一个 Grid 并且在网格中我有子元素。网格有一个 ToolTip,我只想在鼠标指针直接位于 Grid 上方(而不是任何子元素上方)时显示它。

我在下面写了一些 XAML 示例来说明问题。它包含一个 Grid(有 2 列,2 行和一个 ToolTip),以及左上角网格单元格中的 Button

当我将鼠标指针移到 Button 上时,它显示 ToolTip。当我将鼠标指针移到 Grid 上时,它还会显示 ToolTip。我只希望当鼠标直接位于 Grid 上方(而不是 Button 上方时显示 ToolTip

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" 
        Height="350" 
        Width="525">

    <Grid ToolTip="I'm over the grid"
          HorizontalAlignment="Stretch"
          VerticalAlignment="Stretch"
          Background="LightSteelBlue">

        <Grid.RowDefinitions >
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions >
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>

        <Button Grid.Row="0"
                Grid.Column="0"
                Content="MY BUTTON"/>

    </Grid>
</Window>

有一个 IsMouseDirectlyOver property 所以我想知道是否有任何方法可以使用它来仅在鼠标直接位于 Grid 上时显示 ToolTip

只需分离该父关系并将其移动到落后于其他对象的元素,但作为子对象仍将仅接收网格的 MouseOver 和其他元素的 none,一种方法是喜欢;

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" 
        Height="350" 
        Width="525">

    <Grid HorizontalAlignment="Stretch"
          VerticalAlignment="Stretch"
          Background="LightSteelBlue">

        <Grid.RowDefinitions >
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions >
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>

       <Rectangle Grid.RowSpan="2" Grid.ColumnSpan="2" 
                  Fill="Transparent"
                  ToolTip="I'm only shown when I have a mouse on me instead of all the children, because I'm special :)"/>

        <Button Grid.Row="0"
                Grid.Column="0"
                Content="MY BUTTON"/>

    </Grid>
</Window>

希望这对你有帮助,干杯。