wpf 如何从代码隐藏中访问控件模板的元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8126700/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 23:10:17  来源:igfitidea点击:

How do I access an element of a control template from within code-behind

wpfsyntaxuser-controlscode-behind

提问by Locksleyu

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}" />

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?

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

Thanks!

谢谢!

回答by H.B.

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 templateif you are authoring the control that the template is for. Access from outside should be done via bound properties and methods.

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

For data templatesthis 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.

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

回答by Dawid Jablonski

U also can get control from every template by adding Loaded event in control and then in code assign sender of event to some variable.

您还可以通过在控件中添加 Loaded 事件然后在代码中将事件的发送者分配给某个变量来从每个模板中获得控制权。