2010-07-19 66 views
11

有沒有辦法將約束添加到附加的依賴屬性,以便它只能應用於元數據中的特定類型?約束來限制附加依賴屬性的範圍

如果不是,顯式鍵入所連接DP的靜態獲取和設置方法是否有意義?

例子:

如果我有例如下面的聲明:

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

會是meaningfull如下改變它,只能將其應用到文本框?

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可再用於任何類型以及在標記是沒有可能限制attachement。

我之前做過的事情是,我在PropertyChanged處理程序中添加了一個異常,並在那裏引發了一個只允許類型xy的異常。

您認爲如何?

+0

好問題...希望我的新答案可以解決它。 – Noldorin 2010-07-20 07:41:56

+2

對於元數據,我希望得到另一個答案,但我也沒有看到任何東西。對於訪問方法的聲明,我認爲它是一個政策問題。如果這樣做是常識,我會做。但對我來說,它有點像用大鎖關上陽臺,但讓大門解鎖。但至少set和get方法顯示了附加dp的目的。 我將使用您的建議,但繼續檢查PropertyChanged處理程序中的目標類型。因此,如果用戶嘗試在錯誤的控件上使用DP,用戶將會在設計器中收到異常。 – HCL 2010-07-20 08:16:54

回答

15

我相信所有你需要做的,以限制目標類型的附加屬性是改變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繼承。

+2

好吧,不是那麼錯誤......我嘗試使用Visual Studio 2013,並且如果您嘗試將該屬性附加到其他內容,則會出現以下錯誤:**附加屬性「AttachedInt」只能應用於派生自「TextBox」。** – 2013-12-05 12:11:45

+0

Benoit是對的。在VS2013中,XAML intellisense將阻止您將其附加到不受支持的元素。我不使用ReSharper。 – 2015-07-31 06:14:49