简体   繁体   English

如何在wpf中从子用户控件访问父usercontrols元素?

[英]How can I access the parent usercontrols elements from the child user control in wpf?

如何从wpf的子用户控件访问父usercontrol的元素?

Using VisualTreeHelper you can find Parent control's by GetParent() method. 使用VisualTreeHelper ,可以通过GetParent()方法找到父控件。 If you want to find parent control in Templates you can take help of RelativeSource FindAncestor . 如果要在“模板”中查找父控件,可以使用RelativeSource FindAncestor的帮助。

If you need those elements to get their values, eg for binding, you can use this construction (here the background of the element will be using the values of its parent): 如果需要这些元素来获取其值(例如,用于绑定),则可以使用此构造(此处元素的背景将使用其父元素的值):

Background="{Binding Path=BorderBrush, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ComboBox}}}

In the code, for every element extending FrameworkElement class, there is Parent property, just cast it to the correct type (I assume you know, what type it is) and you're done. 在代码中,对于扩展FrameworkElement类的每个元素,都有Parent属性,只需将其强制转换为正确的类型(我想您知道它是什么类型)就可以了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM