附加属性的一个用途是允许不同的子元素为 实际在父元素中定义 的属性指定唯一值。例如:
<DockPanel>
<CheckBox DockPanel.Dock="Top">Hello</CheckBox>
</DockPanel>
<CheckBox DockPanel.Dock="Top">Hello</CheckBox>
</DockPanel>
Dock不是CheckBox的属性,而是定义在DockPanel中的。
用代码使用:
DockPanel myDockPanel = new DockPanel();
CheckBox myCheckBox = new CheckBox();
myCheckBox.Content = "Hello";
myDockPanel.Children.Add(myCheckBox);
DockPanel.SetDock(myCheckBox, Dock.Top);
CheckBox myCheckBox = new CheckBox();
myCheckBox.Content = "Hello";
myDockPanel.Children.Add(myCheckBox);
DockPanel.SetDock(myCheckBox, Dock.Top);
如何创建附加属性
1. 声明一个
2. 使用
public class OwerClass : DependencyObject
{
public static string GetAttachedPropertyName(DependencyObject obj)
{
return (string)obj.GetValue(AttachedPropertyNameProperty);
}
public static void SetAttachedPropertyName(DependencyObject obj, string value)
{
obj.SetValue(AttachedPropertyNameProperty, value);
}
public static readonly DependencyProperty AttachedPropertyNameProperty =
DependencyProperty.RegisterAttached("AttachedPropertyName", typeof(string), typeof(OwerClass), new UIPropertyMetadata(0));
}
{
public static string GetAttachedPropertyName(DependencyObject obj)
{
return (string)obj.GetValue(AttachedPropertyNameProperty);
}
public static void SetAttachedPropertyName(DependencyObject obj, string value)
{
obj.SetValue(AttachedPropertyNameProperty, value);
}
public static readonly DependencyProperty AttachedPropertyNameProperty =
DependencyProperty.RegisterAttached("AttachedPropertyName", typeof(string), typeof(OwerClass), new UIPropertyMetadata(0));
}
小提示:
可以利用VS2008智能提示:在class里面输入propa,然后按Tab 自动生成基本内容:)
WPF界面套包控件:ComponentOne Studio for WPF
中文介绍
WPF界面套包控件:RadControls for WPF
中文介绍
WPF流程图控件:AddFlow for WPF
中文介绍