我使用样式和控件模板创建了一个自定义按钮。我想为此按钮定义一些自定义属性,例如ButtonBorderColour和RotateButtonText。
我该如何做?这可以仅使用XAML完成,还是需要一些C#代码的支持?
我使用样式和控件模板创建了一个自定义按钮。我想为此按钮定义一些自定义属性,例如ButtonBorderColour和RotateButtonText。
我该如何做?这可以仅使用XAML完成,还是需要一些C#代码的支持?
在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); }
}
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" />