简体   繁体   中英

How to add custom XAML attributes to a class that inherits UserControl?

I have a custom UserControl and I want to give it a custom property "MyProperty" which I can set in XAML. So that my XAML will look like this:

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

How do I give the UserControl a custom attribute / property which I can then set in XAML?

If you are using CLRProperty you cannot use for Binding purpose.

 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"/>

只需在您的类中放置一个普通的DependencyProperty

If you just want to set the value from xaml then you can use a regular property. If you want to use the property with triggers, styles, etc then you would need to use a dependency property to take advantage of those WPF features

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM