Tuesday, June 25, 2019

WPF: Validation and Dependency Objects

I recently had to do some support work for a WPF application.  I had not used WPF or MVVM in several years, so it was a nice change.  However, one of the requirements was to create a range validator and attach it to textbox.  The architecture of this part tied the View to the base class of a View Model that had several derived classes.  Each derived class had different minimum and maximum boundaries that needed to be reflected when the view was opened.

There were a couple of very good treatments that I found.  The process is as follows:
  1.  Create the Min and Max Properties in the View Model.
  2.  Create a class derived from ValdationRule.
  3.  Create a wrapper class derived from DependencyObject.  The Dependency Properties will represent the min and max that you need.
  4.  Add a property of the wrapper class in the Validation Rule.
  5.  Create a class derived from Freezable that will enable the View to access the DataContext and pass values to the wrapper.
  6.  Add the elements to the View.  If done properly, the Min and Max needed by the wrapper can be set to values defined in the ViewModel.

No comments:

Post a Comment