WPF - 如何使用模板创建图像按钮 [英] WPF - How to create image button with template
问题描述
我正在尝试创建一个包含 3 个图像的按钮:一个普通图像、一个按下图像和一个禁用图像(我将使用这些图像来创建向上/向下箭头按钮).
I am trying to create a button which has 3 images: a Normal image, a Pressed image and a Disabled image (I will use these for creating up/down arrow buttons).
我相信正确的方法是从 Button
派生并使用 Template
并设置触发器来更改图像.我有 3 个依赖属性,每个图像一个.
I believe the correct approach would be to derive from Button
and use a Template
and set triggers to change the image. I have 3 dependency properties, one for each image.
图像将是 .png 并具有透明背景(因为它们不是矩形).
The images would be .png and have transparent backgrounds (as they are not rectangular).
我正在 MFC 中寻找类似 CBitmapButton
的东西.
I am looking for something like CBitmapButton
in MFC.
推荐答案
您不需要依赖属性,因为您是从 Button
继承的.您已经拥有 IsPressed
和 IsEnabled
属性.事实上,这就是你所需要的:
You won't need dependency properties because you are inheriting from Button
. You already have the IsPressed
and IsEnabled
properties. In fact, this is all you need:
<Button x:Class="TestWpfApplication.ThreeStateImageButton"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Button.Template>
<ControlTemplate TargetType="{x:Type Button}">
<Grid>
<Image Name="Normal" Source="Resources/Normal.png"/>
<Image Name="Pressed" Source="Resources/Pressed.png" Visibility="Hidden"/>
<Image Name="Disabled" Source="Resources/Disabled.png" Visibility="Hidden"/>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsPressed" Value="True">
<Setter TargetName="Normal" Property="Visibility" Value="Hidden"/>
<Setter TargetName="Pressed" Property="Visibility" Value="Visible"/>
</Trigger>
<Trigger Property="IsEnabled" Value="False">
<Setter TargetName="Normal" Property="Visibility" Value="Hidden"/>
<Setter TargetName="Disabled" Property="Visibility" Value="Visible"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Button.Template>
</Button>
使用您的 UserControl 代码隐藏文件:
With your UserControl code-behind file:
public partial class ThreeStateImageButton : Button
{
public ThreeStateImageButton()
{
InitializeComponent();
}
}
这篇关于WPF - 如何使用模板创建图像按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!