You can create resource dictionaries and add as many control style templates to them as you need. Then you can either cause controls to load their template styles dynamically or define specific styles in the design view itself. The examples below illustrate both cases.
Right-click on your existing project, and choose Add Resource Dictionary from the context menu (see Figure 4).
Name the new resource dictionary file ButtonStyles.Xaml, and add the control template styles shown in Listing 2. This resource file will contain four control templates, each of which has its TargetType set to Button.
Note that each control template has a unique key (x:Key) named according to the resulting button style. Choosing good names helps with control template reuse.
At their simplest, control templates let you manage the visual display of a control using styles, triggers—and much more. It's also worth noting that every control has a base rendering template built into the system.
With the new control templates safely stored in an external file, to apply them you now need to load them into the Window containing the buttons. Each resource dictionary that you create to hold style templates—in this example—the button content templates, has to be loaded into the parent container's Resources collection.
In this case, you have two options: You can either load the resources into the Grid's (RootGrid) resource dictionary, which will make the styles available only to the controls inside the Grid control, or you can load them into the Window's (Design.Window1) resource dictionary and make them available to all the Window's child objects. As this example requires the styles only for the buttons in the Grid, the first option seems reasonable.
So, create an event handler for the Window's Loaded event, and add the following code to it:
/// Handles the Loaded event of the Window control.
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/>
/// instance containing the event data.</param>
private void Window_Loaded(object sender, RoutedEventArgs e)
ResourceDictionary buttonStyles = new ResourceDictionary();
buttonStyles.Source = (new Uri(
The preceding code loads the resources into the RootGrid.Resources collection. In the XAML, you can refer to the style as a dynamic resource using the appropriate key:
<Button HorizontalAlignment="Left" Margin="2"
x:Name="button1" Content="Button 1"
Running the application now results in the same screen shown earlier in Figure 3, but this time the application is using styles defined in the external resource dictionary.