I’m working on some code which use DataAnnotation attributes on viewmodels, and overrides some of the attributes programmatically under certain circumstances.
Changing ErrorMessage on various types of ValidationAttributes, no problem.
Changing DataFormatString on DisplayFormatAttributes, no problem.
Changing MinimumLength on a StringLengthAttribute, no problem. But.. MaximumLength does not have a public setter!?
Is there any reason why this one property stands out as having a private setter, when all around it are public? Is there any workaround I can use to programmatically change the maximum length of a StringLengthAttribute?
Since the only public way to set the
MaximumLengthproperty is via the attribute constructor, there’s no programmatic way to change it post-construction. You can always use private reflection to do what you need, assuming that you’re running the code with sufficient trust. If you don’t want to (or can’t) go that route, another option would be to swap view models under the given conditions, rather than just updating the attributes as needed. Then you can just construct the needed attribute for each individual view model, and not worry about changing the attribute itself programmatically.One final option is to actually write your own
StringLengthattribute. You can pretty easliy mimic the functionality of the built-in version, since itsIsValid()method is really straightforward:Mimicing that, but including a
publicsetter on theMaximumLengthproperty should get you what you need.