WPF自定义按钮和DependencyObject

时间:2017-07-20 08:31:11

标签: c# wpf xaml

我正在尝试使用属性Button创建自定义ButtonTheme。 这应该负责按钮的背景。我想在XAML代码中设置它。

我的自定义按钮

public enum Theme
{
    Black,
    White
}

public class BugButton : Button
{
    public string Email { get; set; }
    public string Version { get; set; }
    public Produkte Product { get; set; }
    public static readonly DependencyProperty ButtonThemeProperty = DependencyProperty.Register("ButtonTheme", typeof(Theme), typeof(Theme), new PropertyMetadata(Theme.Black, new PropertyChangedCallback(ValueChanged)));
    public Theme ButtonTheme
    {
        get
        {
            return (Theme)GetValue(ButtonThemeProperty);
        }
        set
        {
            SetValue(ButtonThemeProperty, value);
            ValueChanged(this, new DependencyPropertyChangedEventArgs(ButtonThemeProperty, value, value));
        }
    }

    public BugButton()
    {

    }

    private static void ValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var control = d as BugButton;

        var brush = new ImageBrush();
        if ((Theme)e.NewValue == Theme.White)
        {
            brush.ImageSource = new BitmapImage(new Uri("pack://application:,,,/BugReport;component/Images/bug.png"));
            control.Background = brush;
        }
        else
        {
            brush.ImageSource = new BitmapImage(new Uri("pack://application:,,,/BugReport;component/Images/bug_black.png"));
            control.Background = brush;
        }
    }

    protected override void OnClick()
    { 
        base.OnClick();
        BugWindow bug = new BugWindow(Email, Version, Product);
        bug.ShowDialog();
    }

    public void SetParameters(string aEmail, string aVersion, Produkte aProduct)
    {
        Email = aEmail;
        Version = aVersion;
        Product = aProduct;
    }
}

我想如何在XAML中调用它

<BugReport:BugButton x:Name="B_bug" ButtonTheme="White" Margin="0,8,8,0" Style="{StaticResource HeaderButtonHoverMakeover}" Foreground="White" HorizontalAlignment="Right" Width="25" Height="25" VerticalAlignment="Top" Background="White"/>

问题 The type "Theme" must be derived from "DependencyObject".

所以我想它必须看起来像这样:

public class BugButton : DependencyObject

但是这对我从Button需要的东西不起作用。我在这里缺少什么?

1 个答案:

答案 0 :(得分:3)

您的DependencyProperty.Register调用中存在无效参数,即第三个参数Type ownerType应指示注册依赖项属性的类型(所有者类型)而不是其值类型(由第二个参数Type propertyType指定。此外,所有者类型应来自DependencyObject。现在您将typeof(Theme)作为所有者类型传递(它不是'),因此您会收到错误。

你应该做的是传递typeof(BugButton)作为第三个参数(BugButton是实际的注册类型)而不是:

public static readonly DependencyProperty ButtonThemeProperty =
    DependencyProperty.Register(
        "ButtonTheme",
        typeof(Theme),
        typeof(BugButton),
        new PropertyMetadata(Theme.Black, new PropertyChangedCallback(ValueChanged)));

此外,ValueChanged设置器中对ButtonTheme的调用是多余的。如果值实际发生了变化,框架会在调用SetValue(...)时调用它。