I’ve seen the rumbling a few times now about property setting in Silverlight. The rumblings are along the lines of “why do I have to use SetValue for setting simple properties like the x/y positioning?” To those points, I agree from a fundamental standpoint. From a technical standpoint SetValue is there and serves a great purpose for providing a common way of setting properties on XAML elements regardless of the element. As a developer, I like it actually. I do, however, see the point about wanting to set simple properties and it just looks a little verbose. Take for instance setting the x/y positioning of an Ellipse (in code):
You’ll see the last three lines seem a little verbose when setting simple properties. Most of the time you’ll run into this using your own custom controls or while providing controls to others. Here’s a tip to simplify this process…abstract these simple ones away if you know they will be used frequently.
Developers familiar with Flash/Flex will note that for something like the above example, there are .x and .y values. We can do the same with Silverlight by ensuring our controls follow a pattern we anticipate our developers will use. Let’s say we have a control called MyCircle which contains only an Ellipse. We know that our consumers of our control will be animating our circle control using various calculations and moving x/y coordinates frequently. In our control we can do this (assuming our XAML has an Ellipse in a Canvas element):
Now when developers need to move this control around they can simplify things by writing code like this:
By doing this we’ve abstracted out the SetValue/GetValue functions (while still there if needed) for some simple properties. I like this tip a lot and generally is helpful when you need quick/simple access to properties like this. I learned this tip from Rick Barraza who incidentally does work in Flash, Flex, WPF and Silverlight. He uses this technique when doing a lot of manipulation of objects that involve math, etc. – in the end the result is the same, but this tip might save you some precious keystrokes.
Please enjoy some of these other recent posts...