我正在开发WPF应用程序。在我的应用程序中,我希望按类类型访问对象。
我尝试了下面的代码块。
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;
}
}
}
}在我的申请中,我使用了以下方式。
foreach (Storyboard sb in FindVisualChildren<Storyboard>(window))
{
// There is no accessable storyboard object
}我可以访问Control对象,但不能访问非UIElement对象。例如:我可以找到RadioButton,但找不到Storyboard对象。
发布于 2019-07-10 13:01:48
正如注释中提到的,Storyboard不是添加到可视树中的可视化元素,因此VisualTreeHelper将无法找到它。
但是可以将所有Storyboards添加到窗口的Resources字典中,并遍历资源:
Storyboard sb1 = new Storyboard();
Storyboard sb2 = new Storyboard();
...
Resources.Add("sb1", sb1);
Resources.Add("sb2", sb2);
...
foreach (Storyboard sb in Resources.Values.OfType<Storyboard>())
{
...
}https://stackoverflow.com/questions/56969604
复制相似问题