WPF:图像按钮的可重用模板?

我的WPF项目使用了很多图像按钮,但由于我没有找到正确的方法(我每次都必须编写相同的触发器和样式,只有差异是图像源),我的资源字典变得很长徒劳无功。 有更好的方法吗?

这是我用于按钮的样式示例:

               

谢谢 :)

最简单的方法是使用Image属性创建特定控件:

 public class ImageButton : Button { static ImageButton() { DefaultStyleKeyProperty.OverrideMetadata(typeof (ImageButton), new FrameworkPropertyMetadata(typeof (ImageButton))); } public ImageSource Image { get { return (ImageSource)GetValue(ImageProperty); } set { SetValue(ImageProperty, value); } } public static readonly DependencyProperty ImageProperty = DependencyProperty.Register("Image", typeof(ImageSource), typeof(ImageButton), new PropertyMetadata(default(ImageSource))); } 

然后,您只需在generic.xaml中为它创建一个样式,并绑定到Image属性,而不是显式设置图像:

  

然后你可以像这样使用它:

  

如果需要更多图像用于按钮的不同状态,则可以向控件添加更多依赖项属性。

另一种可能的方法是使用我称之为“参数化样式”的方法,以避免创建特定的控件; 有关详细信息,请参阅此博文 。

您可以尝试创建从Buttoninheritance的自定义控件,并将其用作模板中的TargetType。 然后,您可以在图像源中使用TemplateBinding。

  

您需要在自定义控件中创建ImageSource属性。 这样您就可以在xaml中设置源代码,但只需要一个资源模板。

您可以像这样使用BasedOn属性:

  

这将使Button Style具有与ButtonStyle相同的属性,但具有DeepSkyBlue背景。