簡體   English   中英

wpf定義樣式的自定義屬性

[英]wpf defining custom properties for styles

我已經使用Style和Control模板創建了一個自定義按鈕。 我想為這個按鈕定義一些自定義屬性,如ButtonBorderColour和RotateButtonText。

我該怎么做? 它可以只使用XAML完成,還是需要一些C#代碼?

需要使用DependencyProperty.Register在C#中聲明屬性(或者,如果您沒有創建自定義按鈕tyoe,則使用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); }
}

如果您沒有創建自定義類,但想要定義可以在普通Button上設置的屬性,請使用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" />

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM