Split Generic.xaml in Silverlight Applications
by Loek on January 24, 2012
If you work with Templated controls in a big Silverlight project, your Generic.xaml might grow fast. Here’s a quick tutorial on how to split the Generic.xaml into multiple resource files.
Step1: Find the resource
You will typically have the control code:
public class TemplatedControl1 : Control {
public TemplatedControl1() {
this.DefaultStyleKey = typeof(TemplatedControl1);
}
}
and the XAML in the Generic.xaml:
<Style TargetType="local:TemplatedControl1">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:TemplatedControl1">
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
Step2: Create a new resource file
Create a copy of Generic.xaml and rename to TemplatedControl1.xaml.
Delete the TemplatedControl1 style from Generic.xaml.
So Generic.xaml looks like:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:SilverlightApplication1">
</ResourceDictionary>
and TemplatedControl1.xaml looks like:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:SilverlightApplication1">
<Style TargetType="local:TemplatedControl1">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:TemplatedControl1">
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
Step3: Create reference in App.xaml
Open App.xaml and add the resource:
<Application xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="SilverlightApplication1.App"
>
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source='/SilverlightApplication1;Component/Themes/TemplatedControl1.xaml'/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
</Application>
If you open the project in Expression Blend you will see that you can edit the template as usual:
