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

时间:2015-02-12 15:28:33

标签: wpf xaml

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

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

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

<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所以我很想知道当鼠标直接在ToolTip上方时,我是否可以使用它来显示Grid

1 个答案:

答案 0 :(得分:1)

只需分离父关系并将其移动到一个落在其他对象后面的元素,但作为一个孩子仍将仅为网格接收MouseOver而没有其他元素,一种方式就是这样;

<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>

希望这会有所帮助,欢呼。

相关问题