获取父用户控件的属性值,从孩子的用户控件 [英] Getting value of a property in Parent User control from a Child user control
问题描述
我有一个是一个ParentUserControl内加载的ChildUserControl。主机页面加载ParentUserControl。
I have a ChildUserControl that is loaded inside a ParentUserControl. The host page loads ParentUserControl.
我需要从ChildUserControl访问ParentUserControl属性。
I would need to access properties in ParentUserControl from the ChildUserControl.
感谢您的时间
推荐答案
该平台/语言等不明确,所以这个答案必然是模糊的......不过,一般子控件不能从访问属性母公司(直接),因为很多不同类型的家长控制,可以承载子控件。孩子不应该是硬coded到一个单亲家庭,否则很可能会成为部分母公司。
The platform / language etc isn't clear, so this answer is necessarily vague... however, in general a child control can't access properties from the parent (directly), because lots of different types of parent controls could be hosting the child control. The child shouldn't be hard-coded to a single parent, otherwise it might as well be part of the parent.
通常情况下,你可能想尝试简单地删除的要求 - 这听起来像一个奇怪的设计。然而,一些框架,支持东西的喜欢的这 - 例如,在WPF依赖属性
Generally, you might want to try to simply remove the requirement - it sounds like an odd design. However, some frameworks support something like this - for example, dependency properties in WPF.
这是基于接口的设计(父(多个))是一种方法,但是这不是很干净。对于.NET,事件等都是对孩子与父母沟通另一种常见的方式 - 孩子暴露出其不同的家长可以以不同的方式消耗事件
An interface-based design (for the parent(s)) is one approach, but this isn't very clean. For .NET, events etc are another common way for a child to communicate with a parent - the child exposes events which different parents can consume in different ways.
除此之外,你进入测试区域/压铸父(无论是对一个类或接口),从父访问的细节 - 例如:
Other than that, you're into the territory of testing/casting the parent (either against a class or an interface) to access details from the parent - for example:
ParentControlType parent = this.Parent as ParentControlType;
if(parent != null) {
// access properties etc of "parent"
}
(也可以在这里使用的接口;还是有点哈克无论哪种方式...)
(could also use an interface here; still a bit hacky either way...)
个人,而不是使用这种类型的投自孩子,我想preFER父采取控制;父的子集的属性,并监听事件(而不是子集的属性回父):
Personally, rather than use this type of cast from the child, I'd prefer the parent to take control; the parent sets properties on the child, and listens to events (rather than the child set properties back on the parent):
// in the parent
child.SomeProperty = 132;
child.SomePropertyChangd += delegate {
// do something at the parent
};
这样一来,孩子不知道或关心父母。所有它知道的是,它具有性质(等),并可以通知其他人有趣的变化。
This way, the child doesn't know or care about the parent. All it knows is that it has properties (etc), and can notify other people to interesting changes.
这篇关于获取父用户控件的属性值,从孩子的用户控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!