We pay for user submitted tutorials and articles that we publish. Anyone can send in a contributionLearn More
While working on a complex UI application written in WPF I noticed that because I was using DataTemplates, Control templates and Styles both the Xaml and the Code Behind got very messy.
That is because once you start implementing those Code Behind EventHandlers you basically “mix” code from the template and code from the Window, plus you cannot access the elements in the template from the code behind.
You can move all the Templates and Styles to a ResourceDictionary but then you will not have the code behind available, so Templates that are more complex and interactive can’t go there.
Let’s look at the following example:
This application shows Records with the phone number hidden. Once you click on the “Show Number” Button in the template we change the Visibility of the Number TextBlock to Visible. Done this way you would have to bind the Visibility to a variable in the DataContext and then change it in the code behind of ShowNumber_Click, something like that:
Don’t forget to bind the TextBlock Visibility to the Vis property.
This is simple application but once the window gets “crowded” with templates, styles and the code behind starts to fill with event handlers and variables you get a big mess.
What can you do? Use UserControls.
All you have to do is copy the Template Code into a user control:
And specify this control as the DataTemplate:
We have just separated the Item Code Behind and the Window Code Behind Which I think helps to keep things arranged but, we also got another thing, because they are encapsulated in a UserControl we can access the Controls in the template! We can make the ShowNumber_Click event handler look like this:
Which I personally prefer. I don’t like sticking UI related setting inside the data.
So, by encapsulating the template in a UserControl we have achieved 3 things:
Do you have a better way? Let me know what you think
Tags :Code BehindDataTemplateEventHandlerUIUserControlVisibilityXaml
Copyright © 2012 Dev102.com
Breeze : Designed by Amit Raz and Nitzan Kupererd