April 01, 2009

Creating UserControl to hold other controls in WPF

4 comments

Hi Friends,
You can find many samples in google for creating user controls and my post stands little adhead of them.
Firstly if you create a user control and in the main window where you use the usercontrol, if you try to put some content within your usercontrol, it will throw an error. This is because your usercontrol is not designed to handle other wpf elements within it. To make this happen you have to follow a different apporach.
The following is a sample code for creating such a control:
<USerControl x:Class="MyUserControl" Height="Auto" Width="Auto"......>
<UserControl.Template>
<ControlTemplate>
<Grid>
<Border Height="Auto" Width="Auto" Background="{TemplateBinding Property=ContentControl.Background}" CornerRadius="10">
<ContentPresenter Content="{TemplateBinding Property=ControlContent.Content}" />
</Border>
</Grid>
</ControlTemplate>
</UserControl.Template>

And in your main window just add it as
<MyUserControl Background="LightBlue" Height="50" Width="75">
<Button content="Push Me">
</MyUserControl>

Remember here both MyUserControl and the Main window remain in the same namespace. The result of the above code will be a rounded rectangle with a button inside it. Creating a rounded rectangle as an usercontrol is easy but it will not act like a container for holding for other elements. What the magic i have done here is, i've defined the look of my usercontrol as rounded rectangle inside the usercontrol template and mainly the ContentPresenter Tag which makes the control to hold other items. Other important issue to look at is the TemplateBinding. I will not explain about TemplateBinding for now but you can find many sites that will help you around.
In my next post i'll explain how to change/access the cornerradius of the rectangle from code-behind of the usercontrol which will help you to expose the accessibility to the main window.