tags:

views:

198

answers:

1

When creating a WPF user control, is it possible to make a property required via an attribute or other mechanism?

+1  A: 

Assign the property to an initial value which can be distinguished from any other value that it might be set to (i.e., null for reference types).

At the point when you need the property, if it has not been set (this.Property == UnsetValue), throw an InvalidOperationException with a description of the issue.

Also, make sure this is prominently described in the documentation on the class, on the property, and on any methods that will throw the exception if the property is not set.

**edit Alternatively, you could create an XSD schema for your control that identified the property as required, however I don't know how to go about doing this.

A quicker solution might be to implement ISupportInitialize, which would allow you to check the property during deserialization, at which time you can throw an exception. Here's a post on it at Relyea's blog about it.

Will
Good suggestion, but I'm looking for something that would give an XAML error when they try and compile the Page/Window which uses the control.
Dylan
Hi, Any luck with it? I'm actully looking for the same - code wiil not compile if certian property hasn't been set up from XAML.
Bashir Magomedov