从代码设置silverlight模板? [英] Set silverlight Template from code?

查看:24
本文介绍了从代码设置silverlight模板?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我的模板放在 ResourceDictionary 中,我如何从代码设置 control.Template?

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

推荐答案

从根本上说,您需要附加到控件的加载事件.此时您可以分配给 Template 属性.您可以从资源字典中检索模板.

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.

例如,假设您有一个包含 TextBox 的 UserControl,您希望在 UserControl 的代码中为其提供不同的模板,并且该模板存储在 UserControls Resources 属性中.

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>

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

在这种情况下,我使用文本框自己的加载事件,但是,您也可以使用 UserControls 加载事件.

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

这篇关于从代码设置silverlight模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆