在写代码的时候,有时候我们需要给现有的控件添加一个属性,然后用这个属性记录一些别的值,这时候我们可以继承这个控件,然后再这个控件里面写一个属性。例如我们给Button控件添加一个ButtonTag值,代码如下:
- public class KButton:Button
- {
- private string buttonTag;
-
- public string ButtonTag
- {
- get { return buttonTag; }
- set { buttonTag = value; }
- }
- }
- <Grid>
- <local:KButton ButtonTag="自定义属性" Click="KButton_Click" x:Name="Button1">local:KButton>
- Grid>
运行效果
但是我们想给这个自定义的属性绑定一个值呢,例如
- <Grid>
- <local:KButton ButtonTag="{Binding Message}" Click="KButton_Click" x:Name="Button1">local:KButton>
- Grid>
就会报如下错误,此时我们就需要使用依赖属性
先看下定义依赖属性的语法:
- public string yilaishuxing
- {
- get { return (string)GetValue(yilaishuxingProperty); }
- set { SetValue(yilaishuxingProperty, value); }
- }
-
- // Using a DependencyProperty as the backing store for yilaishuxing. This enables animation, styling, binding, etc...
- public static DependencyProperty yilaishuxingProperty;
- public KButton()
- {
- yilaishuxingProperty =DependencyProperty.Register("yilaishuxing", typeof(string), typeof(KButton),null);
- }
此时前台界面就可以使用binding了
<local:KButton yilaishuxing="{Binding Message}" Content="ssss" Click="KButton_Click" x:Name="Button1">local:KButton>
上面说的是依赖属性,那么什么是附加属性呢,如上ButtonTag是普通的属性,没有办法通过Binding填充数据,此时就可以通过附加属性让ButtonTag支持Binding。代码如下:
- private string buttonTag;
-
- public string ButtonTag
- {
- get { return buttonTag; }
- set { buttonTag = value; }
- }
- public static string GetButtonTagMyProperty(DependencyObject obj)
- {
- return (string)obj.GetValue(ButtonTagMyPropertyProperty);
- }
-
- public static void SetButtonTagMyProperty(DependencyObject obj, string value)
- {
- obj.SetValue(ButtonTagMyPropertyProperty, value);
- }
-
- // Using a DependencyProperty as the backing store for ButtonTagMyProperty. This enables animation, styling, binding, etc...
- public static readonly DependencyProperty ButtonTagMyPropertyProperty =
- DependencyProperty.RegisterAttached("ButtonTag", typeof(string), typeof(KButton), null);
这样只需要再ButtonTag下面加一个附加属性并且绑定ButtonTag,此时ButtonTag就可以支持绑定了,依赖属性和附加属性就这么点东西。