我在WPF方面比较新,有人向我提到了数据表格中的自定义列这个不错的功能。
我的问题是:
我有两个数据库表,一个是员工表(Employee table),另一个是职业表(Occupation table)。
员工表
职业表
正如你所看到的,我有一个外键将这两个表连接起来。在我的应用程序中,我设置了DataGrid的ItemsSource = 员工列表(list of Employees)。我自己定义了列,禁用了AutoGenerateColumns属性。我有4列,
0: TextColumn
1: TextColumn
2: TextColumn
3: ComboBoxColumn
我的问题是,如何将ComboBoxColumn(第四列)的ItemsSource设置为我的职业类(Occupation class)列表,显示外键OccupationID的职业描述,并填充ComboBox中的所有职业描述?
我的代码:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
List<Employee> employees;
private void gridMain_Loaded(object sender, RoutedEventArgs e)
{
employees = EmployeeDataHandler.getAllEmployees();
List<Occupation> occs = OccupationDataHandler.getAllJobs();
dgEmployee.ItemsSource = employees;
}
}
class Employee
{
public int ID { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public int Occupation { get; set; }
}
class Occupation
{
public int ID { get; set; }
public string Description { get; set; }
}
我的XAML代码如下:
<Grid x:Name="gridMain" Loaded="gridMain_Loaded">
<DataGrid x:Name="dgEmployee" HorizontalAlignment="Left" Height="301" Margin="10,10,0,0" VerticalAlignment="Top" Width="498" IsSynchronizedWithCurrentItem="True" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding ID}" ClipboardContentBinding="{x:Null}" Header="System ID"/>
<DataGridTextColumn Binding="{Binding Name}" ClipboardContentBinding="{x:Null}" Header="Name"/>
<DataGridTextColumn Binding="{Binding Surname}" ClipboardContentBinding="{x:Null}" Header="Surname"/>
<DataGridComboBoxColumn ClipboardContentBinding="{x:Null}" Header="Occupation" SelectedValueBinding="{x:Null}" SelectedItemBinding="{x:Null}" TextBinding="{x:Null}"/>
</DataGrid.Columns>
</DataGrid>
</Grid>
非常感谢您抽出时间阅读我的问题。顺便说一下,这些都是虚假数据,所以不用担心截图中的名称。