Introduction
I worked on a project with a lot of binding of ComboBox
es to enumerations, and sometimes these enumerations did not have an enumeration of zero defined, and that caused problems when using the ComponentModel DataAnnotations RequiredAttribute
for new records. The RequiredEnumAttribute ValidationAttribute
solved the problem.
The Code
The code is extremely simple and only has to inherit from the RequiredAttribute
and override
the IsValid
method:
public class RequiredEnumAttribute : RequiredAttribute
{
public override bool IsValid(object value)
{
if (value == null) return false;
var type = value.GetType();
return type.IsEnum && Enum.IsDefined(type, value);;
}
}
Because of this design, every capability of the RequiredAttribute
is available for this ValidationAttribute
.
The Sample
On the bound value for both these cases, the Enum has not been set, so it is at the default value, however, there is no value assigned to 0:
public enum TestEnums { One = 1, Two = 2, Three = 3 }
In the in the upper ComboBox
, a property of TestEnums
Type
is bound to the SelectedItem
DependencyProperty
, and the property uses the Required
decorator. The next ComboBox
is identical, except that it is has the RequiredEnumAttribute
decorator.
Since the DataContext
is a new record and no values have been assigned, the default is 0 for the bound enumeration even if there is enumeration defined for 0. This may acatually good since the develolper may not want to have an initial value set, requiring the user to actually set a value before continuing. The other option is to use a Nullable
enumeration. The advantage of Nullable is that a normal Required decoractor can be used, but then have to ensure that a non-Nullable enumeration base value is appropriately handled.
In the above picture you can see two addtional ComboBox
's bound to an enumeration that has the zero value defined. Both have the [Required]
attribute in the ViewModel
. In the third ComboBox
what happens when there is a default value of zero has been defined, and the enumeration is left at its default value. The last ComboBox
is bound to a Nullable
, and the enumeration has a 0 value defined. The default value in this case is Null, so the Required
attribute generates an error.
History
- 03/10/2016: Initial version
- 08/02/2016: Changed name to
RequiredEnumAttribute