我正在为自己制作一本食谱,用WPF / C#编写。 另外,我是Data Bindings的新手。
我的问题是,我想在代码隐藏的运行时在TabItem中生成一个Datagrid,包括Bindings。我无法在XAML上设置Datagrid,因为我想动态创建所有TabItem。
到目前为止遵守守则:
XAML:
<UniformGrid Columns="2" Rows="1">
<TabControl Name="TabControl" TabStripPlacement="Left"/>
<TabItem Header= "first dish" Name = "firstdish"/>
</UniformGrid>
XAML.cs代:
//New Grid
var Grid = new DataGrid();
//Start Test list creation with three items
var TestList = new List<Receipt>();
//Set binding
Grid.ItemsSource = TestList;
var Rec = new Receipt();
Rec.Creator = "DaJohn1";
Rec.ID = 1;
Rec.Title = "TestReceipt1";
var Rec2 = new Receipt();
Rec2.Creator = "DaJohn2";
Rec2.ID = 2;
Rec2.Title = "TestReceipt2";
var Rec3 = new Receipt();
Rec3.Creator = "DaJohn3";
Rec3.ID = 3;
Rec3.Title = "TestReceipt3";
TestList.Add(Rec);
TestList.Add(Rec2);
TestList.Add(Rec3);
//End Test list creation
//Add Column
var SingleColumn = new DataGridTextColumn();
Grid.Columns.Add(SingleColumn);
SingleColumn.Binding = new Binding("Creator");
SingleColumn.Header = "Creator";
//Add Column
var SingleColumn2 = new DataGridTextColumn();
Grid.Columns.Add(SingleColumn2);
SingleColumn2.Binding = new Binding("Title");
SingleColumn2.Header = "Title";
//Set tabitem content to datagrid
firstdish.Content = Grid;
我得到的只是一个包含四行的数据网格(看起来像项目的数量是正确的),它们都是空的,没有数据可供查看。 我从上周一开始就盯着这个,在任何地方找不到答案。
感谢您的任何想法和解决方案。
答案 0 :(得分:0)
尝试更改
var TestList = new List<Receipt>();
到
var TestList = new ObservableCollection<Receipt>();
因为它会自动通知UI有关更改。 我有一个similar problem项目没有渲染,所以可能就是这样。
答案 1 :(得分:0)
我已经接受了你的代码并检查了你做的一些事情:主要的错误是你的xaml代码中你创建了Tab控件然后把TabItem放在它外面,Tabitem必须在控件里面才能工作正确。所以第一个错误是:
<TabControl Name="TabControl" TabStripPlacement="Left">
<TabItem Header="First dish" Name = "firstdish" />
</TbControl>
在我看来,你需要做的其他事情是:
我使用上述指示和您的代码制作了一个小样本,让您更好地了解其工作原理。你可以在这里下载zip: TestClassDataGrid.zip
答案 2 :(得分:0)
下面的代码应该适合你,
XAML:
<TabControl Name="TabControl" TabStripPlacement="Left">
<TabItem Header= "first dish" Name = "firstdish"/>
</TabControl>
.cs文件
public Window()
{
InitializeComponent();
var Grid = new DataGrid();
//Start Test list creation with three items
var TestList = new List<Receipt>();
//Set binding
Grid.ItemsSource = TestList;
var Rec = new Receipt();
Rec.Creator = "DaJohn1";
Rec.ID = 1;
Rec.Title = "TestReceipt1";
var Rec2 = new Receipt();
Rec2.Creator = "DaJohn2";
Rec2.ID = 2;
Rec2.Title = "TestReceipt2";
var Rec3 = new Receipt();
Rec3.Creator = "DaJohn3";
Rec3.ID = 3;
Rec3.Title = "TestReceipt3";
TestList.Add(Rec);
TestList.Add(Rec2);
TestList.Add(Rec3);
//End Test list creation
//Add Column
var SingleColumn = new DataGridTextColumn();
Grid.Columns.Add(SingleColumn);
SingleColumn.Binding = new Binding("Creator");
SingleColumn.Header = "Creator";
//Add Column
var SingleColumn2 = new DataGridTextColumn();
Grid.Columns.Add(SingleColumn2);
SingleColumn2.Binding = new Binding("Title");
SingleColumn2.Header = "Title";
//Set tabitem content to datagrid
Grid.AutoGenerateColumns = false;
firstdish.Content = Grid;
}