本概述文章介绍 WPF 依赖属性和附件属性如何在 XAML 和代码中实现。
1.依赖属性
在CS文件打出propdp+Tab会自动生成一个依赖属性代码
定义依赖属性+回调实现
public class CustomControl_Button:DependencyObject
{
public static readonly DependencyProperty TextProperty = DependencyProperty.Register(
"Text",
typeof(string),
typeof(CustomControl_Button),
new PropertyMetadata(defaultValue: "button", OnText));
private static void OnText(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
System.Windows.Controls.Button button = d as System.Windows.Controls.Button;
button.Content = e.NewValue;
}
[Category("自定义属性"), Description("Text"), DisplayName("Text")]
public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
}
<local:CustomControl_Button local:CustomControl_Button.Text="123"/>
定义依赖属性+数据绑定实现
public class CustomControl_Button:DependencyObject
{
public static readonly DependencyProperty TextProperty = DependencyProperty.Register(
"Text",
typeof(string),
typeof(CustomControl_Button),
new PropertyMetadata(defaultValue: "button"));
[Category("自定义属性"), Description("Text"), DisplayName("Text")]
public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
}
<local:CustomControl_Button local:CustomControl_Button.Text="123"
Content= "{Binding RelativeSource={RelativeSource Self},Path=(local:CustomControl_Button.Text)}" />
2.附加属性
在CS文件打出propa+Tab会自动生成一个附加属性代码
定义附加属性+回调实现
public class CustomControl_ButtonRegister
{
public static string GetMyProperty(DependencyObject obj)
{
return (string)obj.GetValue(MyPropertyProperty);
}
public static void SetMyProperty(DependencyObject obj, string value)
{
obj.SetValue(MyPropertyProperty, value);
}
public static readonly DependencyProperty MyPropertyProperty = DependencyProperty.RegisterAttached(
"MyProperty",
typeof(string),
typeof(CustomControl_ButtonRegister),
new PropertyMetadata(defaultValue:"button", OnMyProperty));
private static void OnMyProperty(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
System.Windows.Controls.Button button = d as System.Windows.Controls.Button;
button.Content = e.NewValue;
}
}
<local:CustomControl_Button local:CustomControl_ButtonRegister.MyProperty="12"/>
定义注册属性+数据绑定实现
public class CustomControl_ButtonRegister
{
public static string GetMyProperty(DependencyObject obj)
{
return (string)obj.GetValue(MyPropertyProperty);
}
public static void SetMyProperty(DependencyObject obj, string value)
{
obj.SetValue(MyPropertyProperty, value);
}
public static readonly DependencyProperty MyPropertyProperty =DependencyProperty.RegisterAttached(
"MyProperty",
typeof(string),
typeof(CustomControl_ButtonRegister),
new PropertyMetadata(defaultValue:"button"));
}
<local:CustomControl_Button local:CustomControl_ButtonRegister.MyProperty="111"
Content= "{Binding RelativeSource={RelativeSource Self},Path=(local:CustomControl_ButtonRegister.MyProperty)}" />