约束以限制附加依赖项属性的范围

HCL*_*HCL 13 wpf

有没有办法向附加的依赖项属性添加约束,以便它只能应用于元数据中的特定类型?

如果没有,显式键入附加DP的静态Get-and Set-methods是否有意义?

例:

如果我有以下声明:

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("AttachedInt", typeof(int), 
   typeof(Ownerclass), new UIPropertyMetadata(0));
Run Code Online (Sandbox Code Playgroud)

如下更改它是否有意义,只将其应用于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));
Run Code Online (Sandbox Code Playgroud)

我的问题是,因为这会导致不一致,因为GetValue和SetValue可以再用于任何类型,并且在标记中也不可能限制附件.

我以前做过的是我在PropertyChanged处理程序中添加了一个异常,并在那里引发了一个只允许类型为xy的异常.

你怎么看?

Nol*_*rin 17

我相信,为了限制附加属性的目标类型,您需要做的就是更改GetPropertyNameSetPropertyName方法的定义.

例:

public static int GetAttachedInt(MyTargetType obj)
{
    return (int)obj.GetValue(AttachedIntProperty);
}

public static void SetAttachedInt(MyTargetType obj, int value)
{
    obj.SetValue(AttachedIntProperty, value);
}
Run Code Online (Sandbox Code Playgroud)

where MyTargetType可以是继承自的任何类型DependencyObject.

  • 好吧,没那么错......我尝试使用Visual Studio 2013,如果您尝试将该属性附加到其他内容,则会出现以下错误:**附加属性"AttachedInt"只能应用于派生自"文本框".** (2认同)