如何获取 WPF 中组框中的控件列表
在标准 WinForms 开发中,我会执行以下操作:
foreach (Control in groupBox1.Controls)
{
MessageBox.Show(c.Name);
}
在 WPF 中如何执行此操作?我在 GroupBox 中有一个网格,网格中有许多控件(按钮等),但似乎无法弄清楚如何获取每个控件。
In standard WinForms development I would do the following:
foreach (Control in groupBox1.Controls)
{
MessageBox.Show(c.Name);
}
How does a guy do this in WPF? I have a Grid inside the GroupBox and a number of controls in the grid (buttons etc.) but can't seem to figure out how to get each control.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
正如 MSDN 建议的那样,您需要将控件作为
GroupBox
的子项进行迭代。另请注意,您通常需要将Grid
添加到GroupBox
中,以便能够向该GroupBox
添加新控件。因此,您需要获取GroupBox
中Grid
的子级并迭代它们,如下所示:您可能会发现这很有用:http://social.msdn.microsoft.com/Forums /en-US/wpf/thread/93ebca8f-2977-4c36-b437-9c82a22266f6
As MSDN advises, you will need to iterate the controls as children of the
GroupBox
. Also, note that you usually need to add aGrid
into yourGroupBox
to be able to add new controls into thatGroupBox
. So you will need to get the children of theGrid
in thatGroupBox
and iterate through them, something like this:You might find this useful: http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/93ebca8f-2977-4c36-b437-9c82a22266f6
更简单的代码会是这样的
Simpler code would be something like
我知道这是一个旧线程,并且标记为已接受的答案有效,但它可以更简单(简单更好)。
安东尼明白了这个想法,但没有提到需要迭代 GroupBox 内的网格,也没有解释如何实现这一点。
在 XAML 中,为 GroupBox 控件内的主网格指定一个名称(此处假设您将其命名为“GroupBoxGridName”)。这将允许您搜索此网格内的控件,包括主组框网格中任何网格内的控件(递归)。
然后在 C# 代码中执行此操作:
其中 ControlType 可以是通用的 Control 或定义的类型,如 TextBox 或 ComboBox 等。
I know this is an old thread and that the answer marked as accepted works, but it could be simpler (and simple is better).
Anthony got the idea but failed to mention that one needs to iterate on the grid inside the GroupBox and failed to explain how to get there.
In XAML give a name to the main grid inside the GroupBox control (here assuming you named it "GroupBoxGridName"). This will allow you to search for controls inside this Grid including the controls inside any grid in the main group box grid (recursive).
Then do this in the C# code:
Where ControlType can be general as Control or a defined type like TextBox or ComboBox or whatever.
您将查找
.Children
属性,而不是.Controls
。此外,这只会返回一阶子级。如果您确实想要
GroupBox
的所有后代,您将需要递归地查找所有控件的所有子级。Instead of
.Controls
, you'll be looking for the.Children
property.Additionally, that will only return first order children. You'll want to recursively find all children of all controls if you truly want all descendants of the
GroupBox
.