I have a custom ValidationRule that requires access to the ViewModel in order to validate a supplied value in conjunction with other properties of the ViewModel. I previously tr
The problem you are having is that your DataContext is being set after you have created the validation rule and there is no notification that it has changed. The simplest way to solve the problem is to change the xaml to the following:
And then set up the Context directly after setting the DataContext:
public MainWindow()
{
InitializeComponent();
this.DataContext = new MyViewModel();
this.validator.Context = new TotalQuantityValidatorContext { ViewModel = (MyViewModel)this.DataContext };
}
You could actually remove the Context class now and just have a property directly on the ValidationRule containing the ViewModel.
EDIT
Based on your comment I now suggest a slight change to the above code (the XAML is fine) to the following:
public MainWindow()
{
this.DataContextChanged += new DependencyPropertyChangedEventHandler(MainWindow_DataContextChanged);
InitializeComponent();
}
private void MainWindow_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
this.validator.Context = new TotalQuantityValidatorContext { ViewModel = (MyViewModel)this.DataContext };
}
This will update your context whenever your viewmodel changes.