我是WPF新手,我试图在我的TabControl中添加标签。 LoadTable函数返回一个DataTable,其中包含Information,应该为每个Tab表示DataGrid。
for (int i = 1; i <= number_MaxSemester; i++)
{
TabItem item = new TabItem();
// Name of TabItem
item.Header = i + ". Semester";
//Contains the Data from Database
item.DataContext = loadTable();
Tabs.Items.Add(item);
}
loadTable返回Datatable
的函数 public DataTable loadTable()
{
DataTable dt = new DataTable();
try
{
//Open Connection to Database
using (SQLiteConnection con = new SQLiteConnection(cs))
{
//Command string for the Sqlite Command
string query = "SELECT Fach, Note, Statusfach, Versuch from infostudent WHERE username = + '" + UserName.Content + "'";
SQLiteDataAdapter dbAdapter = new SQLiteDataAdapter(query, con);
//Fill Data with SQLite Data
dbAdapter.Fill(dt);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return dt;
}
以下是XAML代码:
<TabControl x:Name="Tabs" Margin="10,61,0,57" Width="584" HorizontalAlignment="Left">
<TabControl.ItemTemplate>
<DataTemplate>
<DataGrid />
</DataTemplate>
</TabControl.ItemTemplate>
</TabControl>
答案 0 :(得分:0)
将TabItem的内容属性设置为您的DataTable:
for (int i = 1; i <= number_MaxSemester; i++)
{
TabItem item = new TabItem();
// Name of TabItem
item.Header = i + ". Semester";
//Contains the Data from Database
item.Content = loadTable();
Tabs.Items.Add(item);
}
...并将DataGrid的ItemsSource属性绑定到TabControl的内容模板中的DataTable的DefaultView:
<TabControl x:Name="Tabs">
<TabControl.ContentTemplate>
<DataTemplate>
<StackPanel>
<DataGrid ItemsSource="{Binding DefaultView}" />
</StackPanel>
</DataTemplate>
</TabControl.ContentTemplate>
</TabControl>