依赖属性的回调函数

IsChecked的内容,如果有数据是True,如果没数据则是False

<StackPanel>
    <TextBox Name="tbox" Text="" local:TextBoxHelper.MonitorTextChange="True"/>
    <CheckBox IsChecked="{Binding ElementName=tbox,Path=(local:TextBoxHelper.HasText)}"/>
</StackPanel>

后台代码

class TextBoxHelper
{
    public static bool GetHasText(DependencyObject obj)
    {
        return (bool)obj.GetValue(HasTextProperty);
    }

    public static void SetHasText(DependencyObject obj, bool value)
    {
        obj.SetValue(HasTextProperty, value);
    }

    public static readonly DependencyProperty HasTextProperty =
        DependencyProperty.RegisterAttached("HasText", typeof(bool), typeof(TextBoxHelper), new PropertyMetadata(false));




    // 添加一个依赖属性用来监听数据变化
    public static bool GetMonitorTextChange(DependencyObject obj)
    {
        return (bool)obj.GetValue(MonitorTextChangeProperty);
    }

    public static void SetMonitorTextChange(DependencyObject obj, bool value)
    {
        obj.SetValue(MonitorTextChangeProperty, value);
    }

    public static readonly DependencyProperty MonitorTextChangeProperty =
        DependencyProperty.RegisterAttached("MonitorTextChange", typeof(bool), typeof(TextBoxHelper), new PropertyMetadata(false, MonitorTextChangedPropertyChanged));

    private static void MonitorTextChangedPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (!(d is TextBox box))
            throw new NotSupportedException();

        if((bool)e.NewValue)
        {
            box.TextChanged += TextChanged;
        }
        else
        {
            box.TextChanged -= TextChanged;
        }
    }

    private static void TextChanged(object sender, TextChangedEventArgs e)
    {
        var box = sender as TextBox;
        // 如果发生了改变,对SetHasText的数据进行变化
        SetHasText(box,!string.IsNullOrEmpty(box.Text));
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值