【问题标题】:Hover over label change rectangle background gradient将鼠标悬停在标签更改矩形背景渐变上
【发布时间】:2011-06-01 14:53:05
【问题描述】:

我有一个矩形,上面有几个标签和图像,我有它,所以当用户将鼠标悬停在矩形上时,背景会变为渐变:

<Rectangle Height="88" HorizontalAlignment="Left" Margin="54,28,0,0" Name="rectangle2" VerticalAlignment="Top"
        Width="327" Cursor="Hand">
    <Rectangle.Style>
        <Style TargetType="{x:Type Rectangle}">
            <Setter Property="Fill" Value="Transparent" />
            <Style.Triggers>
                <Trigger Property="IsMouseOver" Value="True">
                    <Setter Property="Fill">
                        <Setter.Value>
                            <LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1">
                                <GradientStop Color="White" Offset="0.0" />
                                <GradientStop Color="#eee" Offset="1" />
                            </LinearGradientBrush>
                        </Setter.Value>
                    </Setter>
                </Trigger>
            </Style.Triggers>
        </Style>
    </Rectangle.Style>
</Rectangle>

但是,当我将鼠标悬停在矩形上方的标签之一上时,背景渐变不显示。

我想让它在将鼠标悬停在标签和矩形上时显示渐变。

这可能吗?

【问题讨论】:

    标签: c# wpf triggers styles


    【解决方案1】:

    如果“over”是指覆盖而不是在上面,则可以将内容包装在 Grid 中(我猜您也可以这样做,但您应该定义行和列)并使用触发的 DataTrigger如果鼠标在环绕网格上,而不仅仅是矩形本身,例如:

    <Grid HorizontalAlignment="Center" VerticalAlignment="Center">
        <Rectangle Width="100" Height="100" StrokeThickness="1" Stroke="Black">
            <Rectangle.Style>
                <Style TargetType="{x:Type Rectangle}">
                    <Setter Property="Fill" Value="Transparent" />
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding IsMouseOver, RelativeSource={RelativeSource AncestorType=Grid}}" Value="True">
                            <Setter Property="Fill">
                                <Setter.Value>
                                    <!-- Brush here -->
                                </Setter.Value>
                            </Setter>
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </Rectangle.Style>
        </Rectangle>
        <Label Name="label" Content="This is a Label" />
    </Grid>
    

    或者,如果标签被覆盖,您可以通过将IsHitTestVisible 设置为false 来使鼠标事件通过标签。

    【讨论】:

    • 在设计器中,标签设置在矩形上方。 (矩形是“订单”上下文菜单中的“发送到后面”选项)这个网格解决方案效果很好!谢谢。
    • 我添加了另一种方法,它应该更容易工作,除非您需要鼠标能够与标签进行交互。
    • 我不需要交互,所以你的第二种方法效果很好,再次感谢。编辑:从头开始,一些标签确实需要交互,所以第一种方法工作正常。
    【解决方案2】:

    因为其他元素都在矩形的顶部,我认为您需要挂钩到矩形的 PreviewMouseMove 事件。

    UIELement.PreviewMouseMove:http://msdn.microsoft.com/en-us/library/system.windows.uielement.previewmousemove.aspx

    预览活动:http://msdn.microsoft.com/en-us/library/ms752279.aspx

    【讨论】:

    • 感谢您的建议,但将IsHitTestVisible 转为false 解决了我的问题。
    猜你喜欢
    • 1970-01-01
    • 2015-01-14
    • 1970-01-01
    • 1970-01-01
    • 2013-04-28
    • 1970-01-01
    • 1970-01-01
    • 2013-07-10
    • 1970-01-01
    相关资源
    最近更新 更多