我需要一种方法来列出wpf应用程序中的所有命名控件。
在C ++中,我们可以使用资源文件来查看表单上所有控件的列表(或者我被告知)。我需要一种类似的方法来查看wpf应用程序中的控件列表。名称将在数据库中使用,因此我不知道如何获取它们,我只需要自动化它,这样我就不会错过或拼错任何内容。
有没有人对如何做到这一点有任何想法?可能有一个工具在那里可以读取xaml文件并选择名称?
答案 0 :(得分:3)
这会帮助你:
private void ProcessLogicalTree(object current)
{
string elementInfo = current.GetType().Name;
if (current is FrameworkElement)
{
elementInfo += " - Name: " + (current as FrameworkElement).Name;
}
MessageBox.Show(elementInfo);
DependencyObject dependencyObject = current as DependencyObject;
if (dependencyObject != null)
{
foreach (object child in LogicalTreeHelper.GetChildren(dependencyObject))
{
ProcessLogicalTree(child);
}
}
}
这就是你如何使用它:
ProcessLogicalTree(this); // Where 'this' is your Window or your UserControl
优先于Loaded事件或Button_Click事件。
答案 1 :(得分:1)
xaml文件是xml格式。您可以使用任何xml解析器来解析xaml文件。您可能会注意到,并非xaml文件中的所有部分都是控件(元素),并且控件不必具有为其指定的名称。
如果您想要运行它,可以使用已建议的LogicalTreeHelper或VisualTreeHelper。
答案 2 :(得分:0)
有人早些时候发给我了这个:
您可以使用LogicalTreeHelper(或VisualTreeHelper)来递归WPF树并找到您感兴趣的控件。
我不知道您是使用Windows还是ASP.net项目,但这适用于wpf表单项目。