编辑:此控件可以在整个项目中根据需要多次重复使用,它的作用与任何其他控件完全相同,并且与任何其他控件库的使用方式相同。没有边框效果,您可以添加任何您想要的悬停效果。这就是它的工作原理。
将名为 CustomControls 的文件夹添加到您的解决方案中。
在该文件夹中创建一个名为 ImageButton 的自定义控件 (WPF)。自定义控制代码在里面。
现在应该已经在您的项目中创建了一个名为 Themes 的文件夹,其中包含一个名为 generic.xaml 的资源字典。打开它并使用资源字典代码。
现在将它添加到您的窗口标签中
xmlns:b="clr-namespace:MyProject.CustomControls"
现在,您可以在该窗口中多次使用该控件,就像使用常规按钮一样,方法是使用答案末尾的标记结构。
这是我制作的一个,您可以在主窗口中设置图像源、高度和宽度,所有标准按钮事件都在那里。
这是自定义控件
namespace MyProject.CustomControls
{
public class ImageButton : Button
{
public static DependencyProperty SourceProperty =
DependencyProperty.Register(
"Source",
typeof(Uri),
typeof(ImageButton));
static ImageButton()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(ImageButton), new FrameworkPropertyMetadata(typeof(ImageButton)));
}
public Uri Source
{
get { return (Uri)GetValue(SourceProperty); }
set { SetValue(SourceProperty, value); }
}
}
}
这是资源字典中的样式,您可以在触发器部分添加鼠标悬停事件和按钮。按下事件或删除触发器并将它们设置在您的窗口上。
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:b="clr-namespace:MyProject.CustomControls">
<Style x:Key="{x:Type b:ImageButton}" TargetType="{x:Type b:ImageButton}">
<Setter Property="Height" Value="{Binding Path=Height, RelativeSource={RelativeSource TemplatedParent}}"/>
<Setter Property="Width" Value="{Binding Path=Width, RelativeSource={RelativeSource TemplatedParent}}"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type b:ImageButton}">
<Grid x:Name="LayoutGrid">
<Image x:Name="_Image" HorizontalAlignment="Center" VerticalAlignment="Center" Width="{TemplateBinding Width}"
Source="{Binding Path=Source, RelativeSource={RelativeSource TemplatedParent}}" Height="{TemplateBinding Height}"/>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="" TargetName="" Value=""/>
</Trigger>
<Trigger Property="Button.IsPressed" Value="True">
<Setter Property="" TargetName="" Value=""/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
要在你的项目中使用它,请将命名空间添加到窗口中,然后标签将是这样的
<b:ImageButton Source="Image.png" Height="50" Width="50" Click="do_Something"/>