【发布时间】:2018-09-04 12:34:45
【问题描述】:
所以我在 WPF 中相对较新,有人向我提到的一个不错的功能是 datagrids 中的自定义列.. 所以这是我的问题。
我有两个数据库表,一个 Employee 表和一个 Occupation 表。
员工表
职业表
如您所见,我有一个链接两个表的外键。所以在我的应用程序中,我设置了我的 DataGrid ItemsSource = 员工列表。在我的 DataGrid 中,我自己定义了列,我禁用了 AutoGenerateColumns 属性。我有 4 列,
0:文本列
1:文本列
2:文本列
3:组合框列
所以我的问题是,如何将 ComboBoxColumn(第 4 列)的 ItemsSource 设置为我的 Occupation 类的列表,显示外键 OccupationID 中的职业描述?并用所有职业描述填充组合框?
我的代码:
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>
非常感谢您花时间阅读我的问题。附言这都是假数据,所以不要担心截图中的名字
【问题讨论】:
-
使用 linq 并将表连接到一个新列表中并将其用作源。
-
Maybe see this 并搜索“WPF 数据网格绑定组合框”。这是非常普遍的事情,我想你会找到很多例子。
-
我没有看到任何公共外键链接已发布的两个表。
-
感谢您帮助男孩/女孩 :) 非常感谢!
标签: c# wpf data-binding datagrid datagridcomboboxcolumn