简体   繁体   中英

Custom attributes in WPF user control

I want to add custom attributes to my user control such that the UserControl will then use that attribute when displaying (or turning on / off) various options

ie

<toolkit:UC_TitleBar title="My Application Title" showCloseButton="false" />

How do I do this?

What you need are dependency properties

public class UC_TitleBar : UserControl
{
    public static readonly DependencyProperty ShowCloseButtonProperty = DependencyProperty.Register("ShowCloseButton", 
                                                    typeof(Boolean), typeof(UC_TitleBar), new FrameworkPropertyMetadata(false));
    public bool ShowCloseButton
    {
        get { return (bool)GetValue(ShowCloseButtonProperty); }
        set { SetValue(ShowCloseButtonProperty, value); }
    }
}
    //add dependency property
    public static DependencyProperty MyTestProperty;

    //init dependency property in static control constructor
    static MyControl()
    {
         var myTestPropertyMetadata = new FrameworkPropertyMetadata(string.Empty, FrameworkPropertyMetadataOptions.AffectsRender, MyTestPropertyChanged);


                MyTestProperty= DependencyProperty.Register("MyTest",
                                                       typeof(string),
                                                       typeof(MyControl),
                                                       myTestPropertyMetadata );
    }

   //implement property 
    public String MyTest
    {
        get { return (String)GetValue(MyTestProperty); }
        set
        {
            SetValue(MyTestProperty, value);
        }
    }

   //using in xaml
   <MyControls:MyControl MyTest="dfdsf" />

read more about dependency properties in MSDN

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