WPF定义样式的自定义属性

5

我使用样式和控件模板创建了一个自定义按钮。我想为此按钮定义一些自定义属性,例如ButtonBorderColour和RotateButtonText。

我该如何做?这可以仅使用XAML完成,还是需要一些C#代码的支持?

1个回答

5

在C#中,需要使用DependencyProperty.Register(如果您不是创建自定义按钮类型,则使用DependencyProperty.RegisterAttached)来声明属性。如果您正在创建自定义按钮类,则以下是声明:

public static readonly DependencyProperty ButtonBorderColourProperty =
  DependencyProperty.Register("ButtonBorderColour",
  typeof(Color), typeof(MyButton));  // optionally metadata for defaults etc.

public Color ButtonBorderColor
{
  get { return (Color)GetValue(ButtonBorderColourProperty); }
  set { SetValue(ButtonBorderColourProperty, value); }
}

如果您不想创建自定义类,但希望定义可在普通按钮上设置的属性,请使用RegisterAttached:
public static class ButtonCustomisation
{
  public static readonly DependencyProperty ButtonBorderColourProperty =
    DependencyProperty.RegisterAttached("ButtonBorderColour",
    typeof(Color), typeof(ButtonCustomisation));  // optionally metadata for defaults etc.
}

然后可以在XAML中设置它们:

<local:MyButton ButtonBorderColour="HotPink" />
<Button local:ButtonCustomisation.ButtonBorderColour="Lime" />

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接