void Visualize(object CoreObj, object ParentControl)
{
if(CoreObj is typeA)
{
object control1 = new MyControl1(CoreObj);
ParentControl.FirstChild.Children.Add(control1);
foreach (object obj in CoreObj.Children)
{
Visualize(obj, control1);
}
}
else if (CoreObj is typeB)
{
object control2 = new MyControl2(CoreObj);
ParentControl.FirstChild.Children.Add(control2);
foreach (object obj in CoreObj.Children)
{
Visualize(obj, control2);
}
}
}
其中FirstChild始终是容器,无论是StackPanel,Grid还是Canvas,或者其他什么。 我如何得到第一个孩子,更难的部分,如何在对象上做Child.Add()?
我可以在案件中要求其他东西"儿童"是从所有wpf容器中的某个地方继承的,但是我无法找出哪个祖先/接口包含" Children"。或者我可以使用反射......
怎么做?
这是我最后的来源,最后
interface IContain
{
Panel GetMain(); //return main container
}
// ...
void Visualize(object CoreObj, Panel ParentControl)
{
UIElement control = new UIElement();
if (CoreObj is File) { control = new NameSpacer(); } //new NameSpacer(obj);
else if (CoreObj is Namespace) { control = new NameSpacer(); }
else if(CoreObj is Using) { control = new NameSpacer(); }
if (control.GetType() == typeof(UIElement)) return;
ParentControl.Children.Add(control);
FieldInfo finf = CoreObj.GetType().GetField("Children"); if (finf == null) return;
var val = finf.GetValue(CoreObj); if (val.GetType() != typeof(IEnumerable<object>)) return;
if (control is IContain == false) return;
Panel container = ((IContain)control).GetMain();
foreach (object o in val as IEnumerable<object>)
{
Visualize(o, container);
}
}
答案 0 :(得分:0)
StackPanel,Grid和Canvas都来自Panel类。这也是包含Children属性的类。
如果你知道你的论点是一个Panel,你也可以访问Children.First()和Children.Add(..)
答案 1 :(得分:0)
var firstChild = parentControl.Descendants().OfType<Panel>().First();
firstChild.Children.Add(control1);
后代方法利用VisualTreeHelper来获取所有后代,并且必须将其定义为扩展方法:
public static IEnumerable<DependencyObject> Descendants(this DependencyObject element)
{
int childrenCount = VisualTreeHelper.GetChildrenCount(element);
for (int i = 0; i < childrenCount; i++)
{
var visualChild = VisualTreeHelper.GetChild(element, i);
yield return visualChild;
foreach (var visualChildren in Descendants(visualChild))
{
yield return visualChildren;
}
}
}