2011-01-09 48 views
1

我有一個問題。我有dep。支柱。類型列表..附加依賴​​類型(列表<T>)問題

public const string ValidationRulesPropertyName = "ValidationRules"; 


    public static List<ValidationRule> GetValidationRules(DependencyObject obj) 
    { 
     return (List<ValidationRule>)obj.GetValue(ValidationRulesProperty); 
    } 


    public static void SetValidationRules(DependencyObject obj, List<ValidationRule> value) 
    { 
     obj.SetValue(ValidationRulesProperty, value); 
    } 

    public static readonly DependencyProperty ValidationRulesProperty = DependencyProperty.RegisterAttached(
    ValidationRulesPropertyName, 
    typeof(List<ValidationRule>), 
    typeof(CustomGrid), 
    new PropertyMetadata(new List<ValidationRule>())); 

現在,如果我在自定義網格設置一些文本框和ValidationRules

的一個列表內
<Grid> 
<TextBox x:Name="txt1"> 
<ValidationRules> 
<Validation:SomeValidationRule/> 
</ValidationRule> 
</TextBox> 
<TextBox x:Name="txt2"/> 
</Grid> 

確定。現在問題是當我嘗試獲取某些元素的規則列表。如果有txt1和txt2實例,當我獲取驗證規則時,它們都會返回SomeValidationRule的實例。

Grid.GetValidationRules(txt1Instance); 

Grid.GetValidationRules(txt2Instance); 

返回相同的列表。

即使嘗試

Grid.GetValidationRules(new TextBox()); 

我得到SomeValidationRule中只列出alement相同的列表。所以這很奇怪。如果我手動將list設置爲某個元素,那麼該元素具有我設置的那個列表,但其他所有元素都有我在xaml中爲txt1設置的列表。

有什麼想法?謝謝!

+0

你能張貼Grid.GetValidationRules代碼()? – 2011-01-09 22:15:43

+0

這是因爲`PropertyMetadata(new List )`只執行一次,所以只創建一個「新列表」,所有規則都被添加到這個列表中。我沒有答案,但這就是當前行爲發生的原因。 – 2011-01-10 01:12:00

回答

1

試試這個修改: -

public const string ValidationRulesPropertyName = "ValidationRules"; 

    public static List<ValidationRule> GetValidationRules(DependencyObject obj) 
    { 
     object result = obj.ReadLocalValue(ValidationRulesProperty); 
     if (result == DependencyProperty.UnsetValue) 
     { 
      result = new List<ValidationRule>(); 
      obj.SetValue(ValidationRulesProperty, result); 
     } 
     return (List<ValidationRule>)result; 
    } 


    public static void SetValidationRules(DependencyObject obj, List<ValidationRule> value) 
    { 
     obj.SetValue(ValidationRulesProperty, value); 
    } 

    public static readonly DependencyProperty ValidationRulesProperty = DependencyProperty.RegisterAttached(
    ValidationRulesPropertyName, 
    typeof(List<ValidationRule>), 
    typeof(CustomGrid), null); 

該代碼可用於刪除元數據創建List的單個實例並按照列表的創建第一次GetValidationRules被稱爲這反過來又創造如果一個列表,直到尚未創建。

當使用PropertyMetaData時,只能使用不可變類型作爲默認值。

0

您可以在構造函數中設置默認值(並且在定義DependencyProperty時不提供一個值,因爲在這種情況下使用集合實際上設置了單例默認值)。

如果該屬性經常使用,可以避免在get訪問器中進行額外的比較(我猜如果該屬性很少使用,那麼在第一次調用默認值時會按照其他答案中的建議調用它)。

其實這是在花樣微軟在建議: http://msdn.microsoft.com/en-us/library/cc903961(VS.95).aspx