一、附加属性的特点
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>