views:

177

answers:

1

How can i set the control.Template from code if my template is placed in an ResourceDictionary?

+1  A: 

Fundementally you need to attach to the control's loaded event. At this point you can assign to the Template property. You can retrieve the template from a resource dictionary.

For example lets assume you have a UserControl that contains a TextBox that you want to provide a different template for in the UserControl's code and that the template is stored in the UserControls Resources property.

<UserControl xmlns="Namespaces removed for clarity" >
  <UserControl.Resources>
     <ControlTemplate TargetType="TextBox" x:Key="MyTextBox">
       <!-- template mark up here -->
     </ControlTemplate>
  <UserControl.Resources>
  <TextBox x:Name="txt" Loaded="txt_loaded" />
</UserControl>

In the code-behind of the UserControl you would have this code:-

void txt_Loaded(object sender, RoutedEventArgs e)
{
    ((TextBox)sender).Template = (ControlTemplate)Resources["MyTextBox"];
}

In this case I'm using the text box's own loaded event, however, you can also use the UserControls loaded event.

void Page_Loaded(object sender, RoutedEventArgs e)
{
    txt.Template = (ControlTemplate)Resources["MyTextBox"];
}
AnthonyWJones