一、依赖属性
常见可绑定的属性都为依赖属性;
可使用prodp双击Tab键使用代码段快速生成 ;
可通过ICommand命令接口声明一个命令依赖属性,调用命令的Execute()方法去执行绑定的命令方法;
自定义控件添加依赖属性
示例代码:
1、定义
public int DelayTime
{
get { return (int)GetValue(DelayTimeProperty); }
set { SetValue(DelayTimeProperty, value); }
}
// Using a DependencyProperty as the backing store for DelayTime. This enables animation, styling, binding, etc...
public static readonly DependencyProperty DelayTimeProperty =
DependencyProperty.Register("DelayTime", typeof(int), typeof(TimeDisplay), new PropertyMetadata(10));
public ICommand MyCmd
{
get { return (ICommand)GetValue(MyCmdProperty); }
set { SetValue(MyCmdProperty, value); }
}
// Using a DependencyProperty as the backing store for MyCmd. This enables animation, styling, binding, etc...
public static readonly DependencyProperty MyCmdProperty =
DependencyProperty.Register("MyCmd", typeof(ICommand), typeof(TimeDisplay), new PropertyMetadata(null));
2、使用
<local:TimeDisplay Grid.Row="0" MyCmd="{Binding DateCommand}" DelayTime="20"/>
3、扩展
向鼠标双击事件添加一个订阅内容(方法):
MouseDoubleClick += TimeDisplay_MouseDoubleClick;
private void TimeDisplay_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
if (MyCmd != null)
{
MyCmd.Execute(this);
}
}
二、附加属性
常用的附加属性:Grid.Row
可使用propa双击Tab键使用代码段快速生成 ;
自定义控件添加附加属性
示例代码:
1、定义附加属性
public static string GetText(DependencyObject obj)
{
return (string)obj.GetValue(TextProperty);
}
public static void SetText(DependencyObject obj, string value)
{
obj.SetValue(TextProperty, value);
}
// Using a DependencyProperty as the backing store for Text. This enables animation, styling, binding, etc...
public static readonly DependencyProperty TextProperty =
DependencyProperty.RegisterAttached("Text", typeof(string), typeof(CustomControl1), new PropertyMetadata(null));
public override void OnApplyTemplate()
{
var btn = GetTemplateChild("btn") as Button;
btn.Content = GetText(this);
}
2、使用附加属性
<local:CustomControl1 HorizontalAlignment="Center"
VerticalAlignment="Center"
local:CustomControl1.Text="hello" />