TemplateBinding到自定义控件上的DependencyProperty不起作用。

29 浏览
0 Comments

TemplateBinding到自定义控件上的DependencyProperty不起作用。

目前,我正在开发一个简单的自定义按钮,使用用户提供的图像作为按下和正常状态的背景。由于我有很多按钮,所以我决定编写一个自定义按钮,并为按下和正常状态的图片实现两个属性。

以下是我使用的代码:

public partial class ThemeableButton : Button
{
    public ThemeableButton()
    {
        InitializeComponent();
    }
    public static readonly DependencyProperty PressedContentBackgroundSourceProperty = DependencyProperty.Register(
        "PressedContentBackgroundSource", typeof(ImageSource), typeof(ThemeableButton), null);
    public ImageSource PressedContentBackgroundSource
    {
        get { return (ImageSource)GetValue(PressedContentBackgroundSourceProperty); }
        set
        {
            (value as BitmapImage).CreateOptions = BitmapCreateOptions.BackgroundCreation; 
            SetValue(PressedContentBackgroundSourceProperty, value);
        }
    }
    public static readonly DependencyProperty NormalContentBackgroundSourceProperty =
        DependencyProperty.Register("NormalContentBackgroundSource", typeof(ImageSource), typeof(ThemeableButton), null);
    public ImageSource NormalContentBackgroundSource
    {
        get { return (ImageSource)GetValue(NormalContentBackgroundSourceProperty); }
        set
        {
            (value as BitmapImage).CreateOptions = BitmapCreateOptions.BackgroundCreation;
            SetValue(NormalContentBackgroundSourceProperty, value);
        }
    }
}

我为这个按钮编写了以下样式:


我尝试了一个简单的示例


但是图像没有显示出来,我尝试删除样式中的TemplateBinding,并用图像文件的相对路径替换它,效果很好。我只是不想为应用程序中的每个按钮创建自定义样式。有没有可能的解决方法?

0