繁体   English   中英

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

[英]Custom attributes in WPF user control

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

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

我该怎么做呢?

您需要的是依赖项属性

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

阅读有关MSDN中的依赖项属性的更多信息

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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