我很难找出依赖属性的充分理由。为什么 System.Controls.TextBox "Text" 属性是依赖属性而不是普通属性?它作为依赖属性有什么好处?
我要完成的一件事是向我的 UserControl 添加一个 ValidationRules 属性,该属性将包含其他验证规则。像这儿:
<customControls:RequiredTextBox.ValidationRules>
<validators:NotNullOrEmptyValidationRule ErrorMessage="FirstName cannot be null or empty"/>
</customControls:RequiredTextBox.ValidationRules>
问题是我不确定 ValidationRules 属性应该是 DependencyProperty 还是只是一个普通属性。
上面的代码给出了以下错误:
{"Cannot add element to 'ValidationRules'; the property value is null. Error at object 'LearningWPF.ValidationRules.NotNullOrEmptyValidationRule' in markup file 'LearningWPF;component/addcustomerwindow.xaml' Line 35 Position 66."}
这是 ValidationRules 属性:
public static readonly DependencyProperty ValidationRulesProperty =
DependencyProperty.Register("ValidationRules",
typeof (Collection<ValidationRule>), typeof (RequiredTextBox),
new FrameworkPropertyMetadata(null));
public Collection<ValidationRule> ValidationRules
{
get { return (Collection<ValidationRule>)GetValue(ValidationRulesProperty); }
set { SetValue(ValidationRulesProperty, value); }
}