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));
}
}