我正在尝试使用C#中的
WPF为我当前的项目创建GUI.
我想有标签(在运行时动态创建),每个标签应该打开一个具有相同列标题但内容不同的表.
我知道我可以实现这样的标签和表格:
<Grid>
<TabControl x:Name="tabControl" TabStripPlacement="Left">
<TabItem Header="Example 1" x:Name="tabItem" >
<DataGrid ItemsSource="{Binding TagCollection.Tags}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="Tag" Binding="{Binding Tag}" />
<DataGridTextColumn Header="Description" Binding="{Binding Description}" />
<DataGridTextColumn Header="Value" Binding="{Binding Value}" />
</DataGrid.Columns>
</DataGrid>
</TabItem>
<TabItem Header="Example 2" x:Name="tabItem1" >
<DataGrid ItemsSource="{Binding TagCollection.Tags}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="Tag" Binding="{Binding Tag}" />
<DataGridTextColumn Header="Description" Binding="{Binding Description}" />
<DataGridTextColumn Header="Value" Binding="{Binding Value}" />
</DataGrid.Columns>
</DataGrid>
</TabItem>
</TabControl>
</Grid>
如何使用代码生成类似的视图?我还不习惯Bindings等等,所以也许有人可以给我一个简短的例子?
谢谢
KatZe
最佳答案 我已经创建了一个示例项目DynamicTabs.
构造函数中的一些示例上下文:
var tabs = new ObservableCollection<MyTab>();
int tabsCount = 5;
for (var i = 1; i <= tabsCount; i++)
{
var tab = new MyTab() {Header = "Tab " + i};
tab.Data.Add(new MyTabData() {Column1 = "col1" + i, Column2 = "col2" + i, Column3 = "col3" + i});
tabs.Add(tab);
}
DataContext = tabs;
样本上下文的类:
public class MyTab
{
public string Header { get; set; }
public ObservableCollection<MyTabData> Data { get; } = new ObservableCollection<MyTabData>();
}
public class MyTabData
{
public string Column1 { get; set; }
public string Column2 { get; set; }
public string Column3 { get; set; }
}
和XAML:
<Window x:Class="DynamicTabs.MainWindow"
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:local="clr-namespace:DynamicTabs"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<TabControl ItemsSource="{Binding}">
<TabControl.ItemTemplate>
<DataTemplate DataType="local:MyTab">
<TextBlock Text="{Binding Header}"/>
</DataTemplate>
</TabControl.ItemTemplate>
<TabControl.ContentTemplate>
<DataTemplate DataType="local:MyTab">
<DataGrid ItemsSource="{Binding Data}">
<DataGrid.Columns>
<DataGridTextColumn Header="Column 1" Binding="{Binding Column1}" />
<DataGridTextColumn Header="Column 2" Binding="{Binding Column2}" />
<DataGridTextColumn Header="Column 3" Binding="{Binding Column3}" />
</DataGrid.Columns>
</DataGrid>
</DataTemplate>
</TabControl.ContentTemplate>
</TabControl>
ItemTemplate用于TabPage的Header部分和每个TabPage的Content的ContentTemplate.