Is there a way to add a constraint to an attached dependency property so that it only can be applied to a specific type, something in the metadata?
If not, is it meaningful to explicit type the static Get-and Set-methods of the attached DPs?
Example:
If I have for example the following declaration:
public static int GetAttachedInt(DependencyObject obj) {
return (int)obj.GetValue(AttachedIntProperty);
}
public static void SetAttachedInt(DependencyObject obj, int value) {
obj.SetValue(AttachedIntProperty, value);
}
public static readonly DependencyProperty AttachedIntProperty =
DependencyProperty.RegisterAttached("Atta开发者_如何学运维chedInt", typeof(int),
typeof(Ownerclass), new UIPropertyMetadata(0));
would it be meaningfull to change it as follows, to only apply it to TextBoxes?
public static int GetAttachedInt(TextBox textBox) {
return (int)textBox.GetValue(AttachedIntProperty);
}
public static void SetAttachedInt(TextBox textBox, int value) {
textBox.SetValue(AttachedIntProperty, value);
}
public static readonly DependencyProperty AttachedIntProperty =
DependencyProperty.RegisterAttached("AttachedInt", typeof(int),
typeof(Ownerclass), new UIPropertyMetadata(0));
My question is, because this leads to an inconsistence, because GetValue and SetValue could be used anymore for any type and also in markup is no possibility to limit the attachement.
What I did formerly was that I added an exception into the PropertyChanged handler and raised there an exception that only the types xy are allowed.
What do you think?
I believe all you need to do in order to restrict the target type of attached properties is change the definitions of the GetPropertyName
and SetPropertyName
methods.
Example:
public static int GetAttachedInt(MyTargetType obj)
{
return (int)obj.GetValue(AttachedIntProperty);
}
public static void SetAttachedInt(MyTargetType obj, int value)
{
obj.SetValue(AttachedIntProperty, value);
}
where MyTargetType
can be any type inheriting from DependencyObject
.
精彩评论