INotifyDataErrorInfo.GetErrors()调用时机存疑:文档与实际行为不符
GetErrors() is Called During Window Initialization with Mvvm Light and INotifyDataErrorInfo I’ve run into this exact discrepancy before, so I totally get the confusion! Let’s break this down clearly:
First, let’s recap what the official docs state about when GetErrors() gets invoked:
- When a property value is set via the UI
- After the
ErrorsChangedevent ofINotifyDataErrorInfois raised
But when debugging a ViewModel built on Mvvm Light that implements INotifyDataErrorInfo, you’re seeing GetErrors() fire as soon as the window initializes—here’s why that happens:
WPF Binding Engine’s Hidden Initial Check
WPF’s binding system doesn’t wait for user interaction to validate properties. When your window initializes, it resolves the DataContext and sets up all property bindings. For any bound property that uses INotifyDataErrorInfo for validation, the binding engine proactively calls GetErrors() during this initial setup phase. It does this to check for pre-existing validation errors (like invalid initial values set in the ViewModel constructor) so the UI can display them immediately, rather than waiting for user input.
Mvvm Light’s Role in Triggering the Call
If your ViewModel inherits from Mvvm Light’s ViewModelBase, any property you set in the constructor will trigger a PropertyChanged notification (assuming you use the Set() method from ViewModelBase). This notification alerts the binding system that the property’s value has been set, which in turn triggers a validation check—resulting in GetErrors() being called right at startup.
The Docs’ Oversight
The official docs tend to focus on the most explicit trigger scenarios, but they don’t highlight this implicit initialization check. The reality is that GetErrors() is called whenever the binding system needs to know the validation state of a property—and that includes when the binding is first established, not just when the user modifies a value or you explicitly raise ErrorsChanged.
内容的提问来源于stack exchange,提问作者user4266661

