我有一個問題。我有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設置的列表。
有什麼想法?謝謝!
你能張貼Grid.GetValidationRules代碼()? – 2011-01-09 22:15:43
這是因爲`PropertyMetadata(new List)`只執行一次,所以只創建一個「新列表」,所有規則都被添加到這個列表中。我沒有答案,但這就是當前行爲發生的原因。 –
2011-01-10 01:12:00