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

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

问题描述

我正在尝试访问内容控件的控件模板内的用户控件。具体来说:

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天全站免登陆