如何从C#代码将子项添加到UserControl中的StackPanel?我应该为它创建类似DependencyProperty的东西吗?
由于在我的UserControl中很容易设置TextBlock的Text等属性,所以当使用CodeBehind动态添加项目时,我不知道如何向StackPanel添加项目。
StackPanel
仅用于最基本的布局情况。根据您的要求,使用某种ListBox
或ItemsControl
要好得多。您可以在UserControl
中添加一个集合DependencyProperty
,然后执行以下操作:
在UserControl
:中
<ItemsControl ItemsSource="{Binding YourCollectionDependencyProperty, RelativeSource={
RelativeSource AncestorType={x:Type YourPrefix:YourUserControl}}}" ... />
然后,您可以从控制之外将另一个集合属性数据绑定到UserControl
:
UserControl
:外部
<YourPrefix:YourUserControl YourCollectionDependencyProperty="{Binding Items}" ... />
然后添加要在UserControl
中显示的新项目就像将项目添加到Items
集合一样简单:
Items.Add(someNewObject);
有关数据绑定的更多信息,请阅读MSDN上的"数据绑定概述"页面。
是的,你可以这样做(这只是一个示例):
TextBlock printTextBlock = new TextBlock();
printTextBlock.Text = "Hello, World!";
//MainStackPanel below is the name given to your control in xaml
MainStackPanel.Children.Add(printTextBlock);
来源:
- 以程序方式将项目添加到StackPanel