【WPF】用代码给集合(Collection)容器动态添加子元素(Item)
需求:如何向 TabControl 中添加选项卡项。
问题:做的TabControl分页栏想要通过代码来控制添加的子元素。同理可以将解决思路拓展到用于其他的集合控件添加子元素的问题。
在布局文件ShellWindow.xaml中定义了一个TabControl控件,如下:
<Window x:Class="WafApplication1.Presentation.Views.ShellWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:vm="clr-namespace:WafApplication1.Applications.ViewModels"
xmlns:local="clr-namespace:WafApplication1"
mc:Ignorable="d" Title="{Binding Title}" Icon="{StaticResource ApplicationIcon}" Width="800" Height="600"
d:DataContext="{d:DesignInstance vm:ShellViewModel}">
<DockPanel>
<Menu DockPanel.Dock="Top">
<MenuItem Header="_File">
<MenuItem Header="E_xit" Command="{Binding ExitCommand}"/>
</MenuItem>
</Menu>
<!-- 右侧顶部分页栏/分组栏 -->
<TabControl x:Name="tabControl" DockPanel.Dock="Top" Margin="410,0,10,0" Height="300" VerticalAlignment="Top">
</TabControl>
</DockPanel>
</Window>
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using WafApplication1.Applications.Views;
namespace WafApplication1.Presentation.Views
{
public partial class ShellWindow : Window, IShellView
{
private string[] tabItemNames = new string[] {
"户型","空间","造型/材料","品牌","我的空间",
};
public ShellWindow()
{
InitializeComponent();
InitTabControlItemsName();
}
/// <summary>
/// 初始化UI分页栏的各个分页标题
/// </summary>
public void InitTabControlItemsName()
{
int childCount = VisualTreeHelper.GetChildrenCount(tabControl);
for (int i = 0; i < tabItemNames.Length; i++)
{
// 实例化一个分页栏子元素
TabItem item = new TabItem() { Header = tabItemNames[i]};
// 关键点:获取集合控件的子元素集合
ItemCollection coll = tabControl.Items;
// 向集合中添加子元素
coll.Add(item);
}
}
运行之后效果如下:
运行时拖动改变界面的宽高,可以看到选项卡的变化效果如下:
MSDN中该问题的描述: