【问题标题】:Constraint to limit the scope of an attached dependency property限制附加依赖属性范围的约束
【发布时间】:2010-07-19 09:11:55
【问题描述】:

有没有办法为附加的依赖属性添加约束,使其只能应用于特定类型,元数据中的某些东西?

如果不是,显式键入附加 DP 的静态 Get 和 Set 方法是否有意义?

示例:

如果我有例如以下声明:

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));

将其更改如下是否有意义?仅将其应用于文本框?

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));

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

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

你怎么看?

【问题讨论】:

  • 好问题...希望我的新答案能解决它。
  • 对于元数据,我希望有另一个答案,但我也什么也没看到。对于访问方法的声明,我认为这是一个政策问题。如果这样做是常识,我会这样做。但对我来说,这有点像用一把大锁关闭阳台,但不锁大门。但至少 set-and get 方法显示了附加 dp 的目的。我将使用您的建议,但继续检查 PropertyChanged 处理程序中的目标类型。因此,如果用户试图在错误的控件上使用 DP,他将在设计器中收到异常。

标签: wpf


【解决方案1】:

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

例子:

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

public static void SetAttachedInt(MyTargetType obj, int value)
{
    obj.SetValue(AttachedIntProperty, value);
}

其中MyTargetType 可以是从DependencyObject 继承的任何类型。

【讨论】:

  • 好吧,没那么错...我尝试使用 Visual Studio 2013,如果您尝试将属性附加到其他东西,它会给出以下错误:附加属性“AttachedInt”只能应用于从“TextBox”派生的类型。
  • 伯努瓦是对的。在 VS2013 XAML 智能感知将阻止您将其附加到不受支持的元素。我不使用 ReSharper。
猜你喜欢
  • 1970-01-01
  • 2017-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多