【发布时间】:2021-12-03 08:08:20
【问题描述】:
我对 WPF/XAML 有点陌生
我有这个按钮,它包含一个堆栈面板,其中包含一个图像和一个文本框控件。
我在 StaticResource 中设置了按钮样式
如何在 MouseOver 上实现图像更改?
我已完成更改背景颜色和前景色(文本)以在鼠标悬停时更改,但我无法让图像更改工作
这是我的按钮:
<Button Style="{StaticResource mainMenuHomeBtn}">
<StackPanel
Orientation="Horizontal"
HorizontalAlignment="Left">
<Image Name="hjemImage" Margin="5" Height="30" Source="/Images/fal-home-lg-alt.png"/>
<TextBlock Margin="10" VerticalAlignment="Center" Text="Hjem"/>
</StackPanel>
</Button>
这是我的按钮样式:
<Style x:Key="mainMenuHomeBtn" TargetType="{x:Type Button}">
<Setter Property="Width" Value="auto"/>
<Setter Property="Height" Value="auto"/>
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Background" Value="Transparent"/>
<Setter Property="HorizontalContentAlignment" Value="Left"/>
<Setter Property="Padding" Value="-2"/>
<Setter Property="Foreground" Value="#e3e3e3"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border Background="{TemplateBinding Background}" BorderBrush="#cccccc" BorderThickness="0">
<ContentPresenter HorizontalAlignment="Left"/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Foreground" Value="#696969"/>
<Setter Property="Background" Value="#d9d9d9"/>
</Trigger>
<Trigger Property="IsPressed" Value="True">
<Setter Property="Background" Value="#e3e3e3"/>
</Trigger>
</Style.Triggers>
</Style>
【问题讨论】:
-
为了在按钮样式中实现“图像更改”,样式必须声明一个包含图像元素的模板,而不仅仅是一个 ContentPresenter。也许将带有图像的 StackPanel 移动到 ControlTemplate 并使用 ContentPresenter 而不是 TextBlock。
-
你能举个例子吗,因为我是 XAML 和 WPF 的新手? =)
-
stackoverflow.com/a/1933156/1136211 StackOverflow 上有很多类似的东西。
-
没有任何运气。我会选择下一个最好的东西。只需稍微着色我的鼠标悬停背景,这样我就可以使用相同的图片..