我正在创建一个Visual Studio加载项,可以访问当前打开的文件。之后的意图是加载XAML文件,遍历其控件,将每个控件转换为存储在XML文件中的不同格式。
到目前为止,我能够做到这一点。问题是,当我调用FindVisualChildren()方法时,没有返回UIElements。
有什么想法吗?
StreamReader mysr = new StreamReader(pathToXaml);
DependencyObject rootObject = XamlReader.Load(mysr.BaseStream) as DependencyObject;
string s = "";
foreach (UIElement ui in FindVisualChildren<UIElement>(rootObject))
{
s += ui.GetType().Name + "\n";
}
public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
{
if (depObj != null)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
if (child != null && child is T)
{
yield return (T)child;
}
foreach (T childOfChild in FindVisualChildren<T>(child))
{
yield return childOfChild;
}
}
}
}