How can I use my inherited property in a User Control?
I've got a UserControl class called A and that one contains a Border Property. Then others classes are inherited from A class, but I cannot use my new Property.
public class A开发者_JAVA百科 : UserControl
{
public A()
{
Border2 = new Border();
Border2.BorderBrush = Media.Brushes.LightGray;
}
public static readonly DependendyProperty Border2Property = DependencyProperty.Register("Border2", typeof(Border), typeof(A));
public Border Border2
{
get { return (Border)GetValue(Border2Property); }
set { SetValue(Border2Property, value); }
}
}
Then when I use another class where is inherited from A, I cannot use this Border2 Property, I'm writing something like:
<local:A.Border2></...
But it tells me that Border2 property doesn't support values of type Grid.
That's because you've created a standard dependency property. If you want to be able to set it on other types besides A, then you want to create an attached property instead. This only takes a handful of code changes:
- Register it by calling DependencyProperty.RegisterAttached (instead of .Register)
- Add static
GetBorder2
andSetBorder2
methods to class A. Even if your code doesn't call these methods, they're part of the pattern and need to be there -- they're how you tell the compiler that yes, you do intend for people to be able to set this attached property in XAML.
For example:
public static readonly DependencyProperty Border2Property =
DependencyProperty.RegisterAttached("Border2", typeof(Border), typeof(A));
public static Border GetBorder2(DependencyObject obj)
{
return (Border) obj.GetValue(Border2Property);
}
public static void SetBorder2(DependencyObject obj, Border2 value)
{
obj.SetValue(Border2Property, value);
}
If your property should only be available for certain element types -- e.g. if it should only apply to FrameworkElement and its descendants, or to Panel and its descendants, or something like that -- then use that as the type of the first parameter to GetBorder2 and SetBorder2.
精彩评论