WPF用户控件中的自定义属性

时间:2013-03-22 09:34:06

标签: c# wpf user-controls

我想在我的用户控件中添加自定义属性,以便UserControl在显示(或打开/关闭)各种选项时使用该属性

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

我该怎么做?

2 个答案:

答案 0 :(得分:2)

您需要的是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); }
    }
}

答案 1 :(得分:0)

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

详细了解MSDN中的依赖项属性