[英]Adding controls to a child control during runtime
我试图在运行时将一个控件添加到另一个控件。 这是我到目前为止的内容:
必须在.net 3.5中完成
public void addItem(Type addType, Type parentType, string name,string parentName, string fpath)
{
try
{
if (asdf != null)
{
}
else
{
StackPanel stkPnl = (StackPanel)_loadXaml.Content;
foreach (UIElement child in stkPnl.Children)
{
if ((child.GetType() == parentType))
{
Control theChild = (Control)child;
string theChildsName = theChild.Name;
if (theChildsName == parentName)
{
//I want to create and add the control under "theChild"
break;
}
}
}
}
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}
AddType:是控件的类型
parentType:是要添加的对象的父对象的类型。
name:是将要添加的对象的名称
parentName:是创建对象所在的父对象的名称
我已经尝试过.Children.Add不是“ theChild”的选项
.content也不是“ theChild”的选项
有什么方法可以在运行时将控件添加到其父级吗?
您是否尝试过thisChild.AddVisualChild(controlToAdd)?
在这里看到文章
在Wpf中,控件的主要类型有两种:内容控件和项目控件。 内容控件只有一个视觉子级,另一方面,项目控件具有许多视觉子级。 如果要在运行时将项目添加到可视元素中,我认为您必须将该项目转换为项目控件,然后添加所需的项目。 希望这可以帮助您解决问题...
根据您的UI结构,可能会发生许多不同的变化。 某些常见元素类别可能是StackPanel
子元素:
Decorator
-这很可能是Border
但还有其他Border
。 在“ Child
财产中带一个Child
。 Panel
StackPanel
, Grid
, Canvas
等。通过添加到Children
属性中,可以具有任意数量的Children
。 ContentControl
除了使用基类本身之外,还包括诸如Button
, Label
, Expander
类的东西。 可以在Content
属性上接受1个孩子,但是与Decorator.Child
不同,它是Type object
,可以接受任何内容。 所设置的Content
也不像Decorator
那样是直接可见的树状子对象,而是被注入到控件的ControlTemplate
。 如果Content
设置为非UI元素,则还可以使用DataTemplate
进行模板化。 ItemsControl
- ListBox
, ComboBox
, ItemsControl
等。类似于ContentControl
但通过Items或ItemsSource属性获取内容的集合(用法略有不同,只能使用一个或另一个)。 通过添加到Items
或与ItemsSource
绑定的任何集合中来添加子代。 TextBlock
, TextBox
, Slider
以及许多其他子对象。 也有其他可能性,但这是最常见的。 Casting to Control
并没有给您带来任何好处,因为它们可以归入最后3个类别中的任何一个,并且错过了前2个类别中的所有类别。您应该准确定义要在该StackPanel
找到的内容,并限制要使用的类型接受为parentType
,然后parentType
转换为前4种类型之一以设置子代。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.