WPF-关于依赖属性与附加属性

一、依赖属性

常见可绑定的属性都为依赖属性;

可使用prodp双击Tab键使用代码段快速生成 ;

可通过ICommand命令接口声明一个命令依赖属性,调用命令的Execute()方法去执行绑定的命令方法;

自定义控件添加依赖属性

示例代码:

1、定义

        public int DelayTime
        {
            get { return (int)GetValue(DelayTimeProperty); }
            set { SetValue(DelayTimeProperty, value); }
        }
        // Using a DependencyProperty as the backing store for DelayTime.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty DelayTimeProperty =
            DependencyProperty.Register("DelayTime", typeof(int), typeof(TimeDisplay), new PropertyMetadata(10));

        public ICommand MyCmd
        {
            get { return (ICommand)GetValue(MyCmdProperty); }
            set { SetValue(MyCmdProperty, value); }
        }

        // Using a DependencyProperty as the backing store for MyCmd.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty MyCmdProperty =
            DependencyProperty.Register("MyCmd", typeof(ICommand), typeof(TimeDisplay), new PropertyMetadata(null));

2、使用

<local:TimeDisplay Grid.Row="0" MyCmd="{Binding DateCommand}" DelayTime="20"/>

3、扩展

 向鼠标双击事件添加一个订阅内容(方法):

MouseDoubleClick += TimeDisplay_MouseDoubleClick;
        private void TimeDisplay_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (MyCmd != null)
            {
                MyCmd.Execute(this);
            }
        }

二、附加属性

常用的附加属性:Grid.Row

可使用propa双击Tab键使用代码段快速生成 ;

自定义控件添加附加属性

示例代码: 

1、定义附加属性

        public static string GetText(DependencyObject obj)
        {
            return (string)obj.GetValue(TextProperty);
        }

        public static void SetText(DependencyObject obj, string value)
        {
            obj.SetValue(TextProperty, value);
        }

        // Using a DependencyProperty as the backing store for Text.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty TextProperty =
            DependencyProperty.RegisterAttached("Text", typeof(string), typeof(CustomControl1), new PropertyMetadata(null));
        public override void OnApplyTemplate() 
        {
            var btn = GetTemplateChild("btn") as Button;
            btn.Content = GetText(this);
        }

 2、使用附加属性

        <local:CustomControl1 HorizontalAlignment="Center"
                              VerticalAlignment="Center"
                              local:CustomControl1.Text="hello" />

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值