开发者

Set silverlight Template from code?

开发者 https://www.devze.com 2022-12-15 12:05 出处:网络
How can i set the control.Template from code if my template is placed i开发者_StackOverflown an ResourceDictionary?Fundementally you need to attach to the control\'s loaded event.At this point you can

How can i set the control.Template from code if my template is placed i开发者_StackOverflown an ResourceDictionary?


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"];
}
0

精彩评论

暂无评论...
验证码 换一张
取 消