如何从代码隐藏中访问控件模板的元素 [英] How do I access an element of a control template from within code-behind

查看:35
本文介绍了如何从代码隐藏中访问控件模板的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试访问位于内容控件的控件模板内的用户控件.具体:

I'm trying to access a user control which is inside the control template of a content control. Specifically:

  <ContentControl x:Name="MyList" >
        <ContentControl.Template>
            <ControlTemplate x:Name="MyControlTemplate">
                <Border RenderTransformOrigin="0,0" x:Name="border">
                    <UserControls:MyControl x:Name="MyControlName" Width="100" ViewModel="{Binding}" />

我可以访问 this.MyList 但它说没有找到 this.MyControlName.在这种情况下,如何从代码隐藏访问 MyControlName 对象?

I can access this.MyList but it says this.MyControlName is not found. How do I access the MyControlName object from code-behind in this situation?

谢谢!

推荐答案

您需要获取模板并在模板化控件上按名称定位控件,例如:

You need to get the template and locate the control by name on the templated control, something like:

var template = MyList.Template;
var myControl = (MyControl)template.FindName("MyControlName", MyList);

模板就是:对要创建的内容的抽象描述,模板中的控件仅存在于正在模板化的内容的上下文中.

Templates are just that: Abstract descriptions of what is to be created, the controls in templates only exist in the context of something that is being templated.

请注意,如果您正在创作模板所针对的控件,则您应该只访问控件模板中的元素.从外部访问应该通过绑定的属性和方法来完成.

Note that you should only ever access the elements within a control template if you are authoring the control that the template is for. Access from outside should be done via bound properties and methods.

对于数据模板来说,这是类似的.您需要访问的所有内容都应该绑定到一个对象,然后访问应该通过该对象.对于虚拟化其项目的项目控件而言尤其如此,因此大多数时间元素甚至不存在.

For data templates this is similar. All the things you need to access should be bound to an object and access should then be through said object. This is especially true in cases of item controls which virtualize their items, so the elements do not even exist most of the time.

这篇关于如何从代码隐藏中访问控件模板的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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