Cover

XAML Control Design

June 26, 2008
No Comments.

I’ve been digging into some of the open source and 3rd party controls that are becoming available for Silverlight 2. While running into some odd issues with some of them it occurred to me that there are some design guidelines that haven’t been well communicated. Back in the early days of WPF I learned (though exactly where is unclear) that every control should support an empty constructor and that all properties (e.g. XAML Attributes) should have a default value. I knew this to be true but I couldn’t document where it came from.

So as usual when I am stuck, I contacted Chris Sells as he was my mentor in early XAML usage. He was at MSDN at the time gathering content and helped me get the Data Binding articles as well into the Software Design Review for WPF (then Avalon). If anyone could help me figure out where I learned this, he’d know. He reminded me of the language they use internally: “Create-Set-Use”. Essentially this means that the design pattern for controls is that they should work without requiring any properties:

<Grid ...>
  <Rectangle />
</Grid>

You can see that the Rectangle doesn’t require any properties to be valid. Of course this Rectangle has no fill brush and no stroke brush which means it will likely not be visible.  But that’s OK because it is valid XAML and doesn’t break.  The XAML for a control doesn’t have to read the mind of the user, but should behave (e.g. not throw exceptions). One of the most egregious was a control that threw an exception if I failed to set the Width and Height. Worse yet, when it did throw these exceptions, it didn’t tell me what *all* the properties I needed therefore it was painful to use.  Width and Height are particularly problematic in this way in that by not defaulting to “Auto”, showing the control in a non-Canvas container meant I needed to set “Auto” to the values which is what they should *always* be defaulted to.

Create-Set-Use happens during parsing of the XAML. This comes back to thinking of XAML as a serialization format for in-memory objects. XAML is simply a way to define what the structure of a particular document should be when its de-serialized. If you keep in mind that an Element becomes an object construction and that properties become SetValue calls, it makes it fairly clear what is happening during the parsing of the XAML itself.

As you write your own Silverlight or WPF classes that you expect to be used in XAML (this includes controls but also may be types that can be created as resources), try to keep these design ideas in mind. It will make life easier for your users.