【问题标题】:Style with arrow when mouse hover on button, wpf鼠标悬停在按钮上时带箭头的样式,wpf
【发布时间】:2012-12-02 04:02:21
【问题描述】:

我在 WPF 中有这样的 ImageButton

<Image HorizontalAlignment="Left" Height="31.627" VerticalAlignment="Top" Width="32" Margin="21,80.373,0,0" Source="Images\computer.png"/>
<Button FontWeight="Bold" FontSize="12" Content=swethapilli" Height="31.627" VerticalAlignment="Top" Margin="57,80.373,95.296,0"/>

现在看起来像这样:

现在我的要求是当鼠标悬停在ImageButton 上时。当箭头图像与下图相同时,文本 (swethapilli) 应向右移动并突出显示。

如何获得这种风格,请任何人帮助我找到解决方案。谢谢。

【问题讨论】:

  • 图片是按钮的一部分?
  • 不,我只使用几何绘图准备了箭头图像
  • 我的意思是上图中的图像。
  • 是的..它应该是按钮的一部分。

标签: wpf image xaml button mouseevent


【解决方案1】:

我认为最简单的方法是创建一个可以在鼠标悬停时用作按钮背景的图像,如下所示:

    <Style x:Key="SwitchButtonStyle" TargetType="Button">
        <Style.Triggers>
            <Trigger Property="IsMouseOver" Value="True">
                <Setter Property="Background">
                    <Setter.Value>
                        <ImageBrush ImageSource="yourimagepath.ending"></ImageBrush>
                    </Setter.Value>
                </Setter>
                <Setter Property="HorizontalContentAlignment" Value="Right"/>
            </Trigger>
         </Style.Triggers>
     </Style>

编辑:定位内容的更灵活方法如下:

以 TextBlock 作为按钮内容:

            <Button.Content>
                <TextBlock Text="YourTextOrBinding" Style="{DynamicResource ResourceKey=TextBlockOnButtonStyle}"></TextBlock>
            </Button.Content>

TextBlockOnButtonStyle:

    <Style x:Key="TextBlockOnButtonStyle" TargetType="TextBlock">
        <Style.Triggers>
            <DataTrigger Binding="{Binding RelativeSource={RelativeSource AncestorType={x:Type Button}}, Path=IsMouseOver}" Value="True">
                <Setter Property="Margin" Value="10,0,0,0"></Setter>
            </DataTrigger>
        </Style.Triggers>
    </Style>

setters 值中的 10 是当鼠标悬停在按钮上时文本向右移动的像素数。

编辑 2:如果您想使用矩形而不是整个图像作为按钮背景,您可以这样做:

        <DockPanel Width="100" Height="30">
            <Rectangle Visibility="{Binding ElementName=btnMain, Path=IsMouseOver, Converter={StaticResource ResourceKey=BoolToVis}}" Width="25">
                <Rectangle.Fill>
                    <whateveryouwanttousetofilltheimage>
                </Rectangle.Fill>
            </Rectangle>
            <Button Name="btnMain" Content="YourContentOrBinding"/>
        </DockPanel>

在这里,我将矩形的 Visibility 绑定到按钮 IsMouseOver-property 并使用 BooleanToVisibilityConverter 转换输出。

【讨论】:

  • 感谢您的评论。在这里,您更改了背景并替换为图像。我准备了箭头的图像。但是如何将图像与矩形和矩形宽度与按钮的内容相结合。
  • 为什么需要一个矩形?
  • 我想将矩形与箭头图像结合起来,因为当鼠标悬停在按钮上时我不需要单独出现箭头。
  • 为什么不制作一个由灰色区域、箭头和蓝色区域组成的图像?所以你不需要一个矩形。
  • 除非图像是矢量,否则可能不想为此使用图像。它不会随着 DPI 的变化而扩展。
猜你喜欢
  • 2021-01-21
  • 2019-09-02
  • 2010-12-11
  • 1970-01-01
  • 1970-01-01
  • 2011-02-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多