Navigation |
Tag, you are not itIn WPF and Silverlight 2.0 Beta 1, the FrameworkElement class provides a Tag property. From the Silverlight 2.0 documentation on MSDN:
The Tag property allows you to link a domain object to a control (in WinForms and WPF), or even to provide an event handler with a marker to aid in code reuse (e.g. you have several buttons, and the share the same click handler code, which checks the tag to determine how to proceed). In Silverlight, the Tag property is limited (from MSDN):
If you want to attach some arbitrary domain object or data to a control, you might think that you have to resort to the old OO practice of derive and extend. Derive a new control from some existing control, and add your own custom property. An arguably more elegant way to attach a custom property to an existing control is to use (wait for it) a custom Attached Property. For this example, I'm going to return the bit of the sample code I borrowed from WPF in Action with Visual Studio 2008. The sample code builds a simple calculator user interface, then proceeds to use custom attached properties to define the calculator operations.
In the Tag based implementation of of the Calculator, the divide operator button is defined with (see Page_step_one.xaml and .cs in the attached project):
And the ClickOperator() event handler is implemented with:
To convert the calculator to use a custom attached property for the operation value, we first need to define an Enum and then create a dependency property (Operator.cs): [update: The IValueConverter is not needed for this project. See Conversion Conversation.] Before we can use this new attached property in xaml, we need to define a value converter (OperationConverter.cs):
Finally, we can use the new attached property in our xaml:
and in our click event handler:
A custom attached property is the tool of a Silverlight/WPF developer. Not as clumsy or random as a Tag, but an elegant tool for a more civilized technology. Published May 18, 2008
Trackback URL for this post:http://www.exotribe.com/trackback/73 Tim Binkley-Jones sent in a Tip of the Day that custom attached properties make a superior choice to |
Recent blog postsUser login |
Not so sure about
Not so sure about IValueConverter. It seems very unlikely it's involved. IValueConverter is for doing type-change operations specifically for bindings, and even so needs to be implemented on a specific Converter class object, instantiated, and referenced as a property of an individual Binding. Did you try this without?
I am pretty sure that for enums you get 'type conversion' for free based on returning value out of enum membername, even for a custom enum.
OperationConverter is not required
In this example, the OperationConverter is not required, and the code is not called. I guess I'd better read up a bit more on when, where and how to use value converters. Sounds like another blog entry.
Tim
So the dark side uses Tags?
So the dark side uses Tags?