【发布时间】:2019-07-28 21:46:21
【问题描述】:
我正在尝试创建一个 UI,其中有一个 TabControl,并且在每个选项卡中都有一个 DataGrid。我想向 DataGrid 动态添加/删除选项卡以及行/列。下面是代码示例:
Test.xaml
<StackPanel>
<Button x:Name="Button" Content="Add tab" Click="Button_Click"/>
<Controls:MetroAnimatedTabControl x:Name="TabControl"
TabStripPlacement="Left"
DisplayMemberPath="TabName">
<TabControl.ContentTemplate>
<DataTemplate>
<DataGrid AutoGenerateColumns="True" DataContext="{Binding Context}" />
</DataTemplate>
</TabControl.ContentTemplate>
</Controls:MetroAnimatedTabControl>
</StackPanel>
还有代码隐藏
Test.xaml.cs
public class Tab
{
public string TabName { get; set; }
public DataTable Content { get; set; }
public Tab(string name, DataTable content)
{
TabName = name;
Content = content;
}
public Tab(string name, List<string[]> content)
{
Content = new DataTable();
foreach (var item in content){
Content.Columns.Add(item[0], typeof(string));
}
DataRow row = Content.NewRow();
foreach (var item in content)
{
row[item[0]] = item[1];
}
Content.Rows.Add(row);
TabName = name;
}
}
public partial class Test: UserControl
{
ObservableCollection<Tab> clsTabs = new ObservableCollection<Tab>();
public Test()
{
InitializeComponent();
DataTable table = new DataTable();
clsTabs.Add(new Tab("Animals", new List<string[]>() { new string[] { "Name", "Tiger" }, new string[] { "Tail", "Yes" } }));
clsTabs.Add(new Tab("Vegetables", new List<string[]>() { new string[] { "Name", "Tomato" }, new string[] { "Color", "Red" }, new string[] { "Taste", "Good" } }));
clsTabs.Add(new Tab("Cars", new List<string[]>() { new string[] { "Name", "Tesla" } }));
TabControl.DataContext = clsTabs;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
clsTabs.Add(new Tab("New", new List<string[]>() { new string[] { "Name", "Something" }, new string[] { "Detail", "No" } }));
}
}
它可以编译,但是当您运行应用程序时,窗口中没有显示任何内容。数据绑定很可能是错误的(尤其是对 DataGrid,因为我不知道如何使用像我这样的类来做到这一点)。
如果从代码中不清楚,在我的Tab 类中,我有TabName 属性作为选项卡名称,Content DataTable 应该是相应DataGrid 中的数据源。而且我想以某种方式将它们绑定到 xaml,如果实例被修改,UI 也会更新。
是否可以这样做,还是我需要采取不同的方法?
【问题讨论】:
-
尝试使用
更新数据模板定义并设置 DataGrid 的 ItemsSource 属性 -
@NthDeveloper 试过了,但没有运气,仍然只显示一个空的 DataGrid
标签: c# wpf data-binding datagrid mahapps.metro