2011-05-09 63 views
4

我有一個自定義UserControl,我想給它一個自定義屬性"MyProperty",我可以在XAML中設置它。所以,我的XAML看起來像這樣:如何將自定義XAML屬性添加到繼承UserControl的類中?

<EventDet:EventAddressControl 
      MyCustomProperty="formattype"  
      x:Name="EventSessionLocationControl"/> 

如何給用戶控件的自定義屬性/屬性,我可以在XAML然後設置?

回答

8

如果您使用的是CLRProperty,那麼您不能用於綁定目的。

public partial class MyCustomControl : UserControl 
{ 
    public MyCustomControl() 
    { 
     InitializeComponent(); 
    } 

    public string MyCLRProperty { get; set; } 

    public string MyProperty 
    { 
     get { return (string)GetValue(MyPropertyProperty); } 
     set { SetValue(MyPropertyProperty, value); } 
    } 

    // Using a DependencyProperty as the backing store for MyProperty. This enables animation, styling, binding, etc... 
    public static readonly DependencyProperty MyPropertyProperty = 
     DependencyProperty.Register("MyProperty", typeof(string), typeof(MyCustomControl)); 
} 
<my:MyCustomControl MyProperty="{Binding BindingProperty}" 
        MyCLRProperty="MyCLRProperty"/> 
+0

並不完全正確,取決於你使用的是什麼模式,你用的是什麼作爲源/目標。 – 2011-05-09 15:40:06

+0

它不工作,不應該是一個AttachedProperty? – 2013-02-26 08:46:07

1

如果您只是想從xaml中設置值,那麼您可以使用常規屬性。如果你想使用觸發器,樣式等屬性,那麼你將需要使用依賴項屬性來利用這些WPF功能。

相關問題