在XAML中获得子控件的更聪明的方法是什么? [英] What is a smarter way to get a child control in XAML?

查看:40
本文介绍了在XAML中获得子控件的更聪明的方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用户控件,其中包含一个网格,其中包含一个子控件.

I have a User Control, containing a Grid, containing a child control.

我想从用户控件后面的代码中获得对子控件的引用.

I want to get a reference to the child control from the code behind for the User Control.

这就是我所拥有的:

var childControl = (MyChildControlType)this.Grid.Children.Single(c => (string) c.GetValue(NameProperty) == "MyChildControlNameFromXAMLNameAttribute");

丑陋的垃圾桶盖.

什么是更整洁的方式呢?

What is a neater way to do this?

推荐答案

为XAML中的元素分配名称或x:Name(除非它在模板内部)使该元素可以从代码隐藏区作为具有该字段的字段进行访问姓名.因此,在InitializeComponent期间基本上已经为您声明并填充了它:

Assigning a Name or x:Name to an element in XAML (unless it is inside a template) makes that element accessible from code-behind as a field with that name. So this is basically already declared and populated for you during InitializeComponent:

MyChildControlType MyChildControlNameFromXAMLNameAttribute;

,您可以直接使用它:

MyChildControlNameFromXAMLNameAttribute.Visibility = Visibility.Hidden;

这篇关于在XAML中获得子控件的更聪明的方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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