WPF附加属性的使用

一、附加属性的特点
1、特殊的依赖属性
2、用于非定义该属性的类 例如Grid面板的RowDefinition、ColumnDefinition、Canvas面板的Left、Right
DockPanel面板的Dock都是附加属性。

二、附加属性的定义

1、声明数据属性变量。 public static 的DependencyProperty类型的变量。
2、在属性系统中进行注册,使用DependencyProperty.RegisterAttached()方法来注册,方法参数和注册依赖属性时Register()方法的参数一致。
3、调用静态方法设置和获取属性值。通过调用DependencyObject的SetValue()和GetValue()方法来设置和获取属性的值。
两个方法应该命名为SetPropertyName()方法和GetPropertyName()方法。

三、示例演示附加属性

    public class TextBoxHelper
    {
        public static bool GetHasText(DependencyObject obj)
        {
            return (bool)obj.GetValue(HasTextProperty);
        }
        private static void SetHasText(DependencyObject obj, bool value)
        {
            obj.SetValue(HasTextPropertyKey, value);
        }
        public static readonly DependencyPropertyKey HasTextPropertyKey = DependencyProperty.RegisterAttachedReadOnly("HasText", typeof(bool), typeof(TextBoxHelper), new PropertyMetadata(false));
        /// <summary>
        /// 只读附加属性
        /// </summary>
        public static readonly DependencyProperty HasTextProperty = HasTextPropertyKey.DependencyProperty;
        public static void SetMonitorTextChange(DependencyObject obj, bool value)
        {
            obj.SetValue(MonitorTextChangeProperty, value);
        }
        /// <summary>
        /// 订阅(只写附加属性)
        /// </summary>
        public static readonly DependencyProperty MonitorTextChangeProperty =
            DependencyProperty.RegisterAttached("MonitorTextChange", typeof(bool), typeof(TextBoxHelper), new PropertyMetadata(false,MonitorTextChangePropertyCallback));

        private static void MonitorTextChangePropertyCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if(d is TextBox textBox)
            {
                if ((bool)e.NewValue)
                {
                    textBox.TextChanged += TextChanged;
                }
                else
                {
                    textBox.TextChanged -= TextChanged;
                }
            }
            else
            {
                throw new NotSupportedException();
            }
        }

        private static void TextChanged(object sender, TextChangedEventArgs e)
        {
            if(sender is TextBox textBox) 
            {
                SetHasText(textBox,!string.IsNullOrWhiteSpace(textBox.Text));
            }
        }
    }
    <StackPanel>
        <TextBox Name="textBox" local:TextBoxHelper.MonitorTextChange="True" />
        <CheckBox IsChecked="{Binding ElementName=textBox, Path=(local:TextBoxHelper.HasText), Mode=OneWay}" />
    </StackPanel>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值