如何以编程方式展开窗口中的所有扩展器
本文关键字:扩展器 开窗口 编程 方式展 | 更新日期: 2023-09-27 18:37:26
我有一个窗口,里面有一些扩展器。当您打开扩展器时,其中会有一些信息。
我需要做的是用一个按钮打开所有扩展器,以便它们中的所有内容都可见。当所有内容都可见时,我想打印整页。
这是我现在扩展所有扩展器的代码:
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 (Expander exp in FindVisualChildren<Expander>(printpage))
{
exp.IsExpanded = true;
}
现在进入正题:
上面的代码在大多数情况下都有效。我唯一的问题是有时扩展器中有一些扩展器。执行上述代码时,父扩展器确实会扩展,但子扩展器仍保持未展开状态。
我希望有人能教我如何扩展这些儿童扩展器。
编辑
我忘了提到儿童扩展器不是主要扩展器的直接子项。
他们是主要扩张者的孩子。
我的控制树是这样的:
-堆叠面板
---列表项
-----网 格
-------扩展器(主扩展器)
---------网 格
-----------文本块
-------------膨胀
所以我需要展开此树中的所有扩展器。
您的代码已经非常复杂了。如果你调用,收益率是绝对没有必要的,你真的应该以递归的方式执行你的方法。
当您在方法中遇到包含子项的控件时,调用相同的方法,但具有新的可视根,该根将是包含刚找到的子项的控件。
这应该对您有用(可能是一些语法错误,但我相信您是否可以修复它们)
foreach (Expander exp in FindVisualChildren<Expander>(printpage))
{
exp.IsExpanded = true;
for(int i =0;i<exp.Children.Count;i++)
{
if(exp.Children[i] is Expander)
{
expandChildren(exp.Children[i]);
}
}
}
private expandChildren(Expander exp)
{
exp.IsExpanded = true;
for(int i =0;i<exp.Children.Count;i++)
{
if(exp.Children[i] is Expander)
{
expandChildren(exp.Children[i]);
}
}
}
好的,我在这篇文章中找到了我的 anwser
关于这个问题的解释是我用来解决问题的方法。
这是我使用的功能:
public static List<T> GetLogicalChildCollection<T>(object parent) where T : DependencyObject
{
List<T> logicalCollection = new List<T>();
GetLogicalChildCollection(parent as DependencyObject, logicalCollection);
return logicalCollection;
}
private static void GetLogicalChildCollection<T>(DependencyObject parent, List<T> logicalCollection) where T : DependencyObject
{
IEnumerable children = LogicalTreeHelper.GetChildren(parent);
foreach (object child in children)
{
if (child is DependencyObject)
{
DependencyObject depChild = child as DependencyObject;
if (child is T)
{
logicalCollection.Add(child as T);
}
GetLogicalChildCollection(depChild, logicalCollection);
}
}
}
在我的代码中,我使用这些行将我需要的内容附加到我的扩展器中:
List<Expander> exp = GetLogicalChildCollection<Expander>(printpage.StackPanelPrinting);
foreach (Expander exp in expander)
{
exp.IsExpanded = true;
exp.FontWeight = FontWeights.Bold;
exp.Background = Brushes.LightBlue;
}