5

依存関係プロパティの正当な理由を理解するのに苦労しています。System.Controls.TextBox の "Text" プロパティが依存プロパティであり、通常のプロパティではないのはなぜですか? 依存関係プロパティであることには、どのような利点がありますか?

私が達成しようとしていることの 1 つは、ValidationRules プロパティを他の検証ルールを含む UserControl に追加することです。ここみたいに:

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

3 に答える 3

2

バインディングを使用してプロパティの値を設定する場合は、依存関係プロパティが必要です。たとえば、それが単なる通常のプロパティである場合、Text プロパティを View Model オブジェクトのプロパティにバインドすることはできません。

于 2009-06-26T16:32:16.160 に答える