DataGridComboBoxColumn绑定到DataGrid ItemsSource的不同列表

问题描述 投票:0回答:1

所以我在WPF中相对较新,有人向我提到的一个很好的功能是datagrids中的自定义列。所以这是我的问题。

我有两个数据库表,一个Employee表和一个Occupation表。

员工表

Employee table

职业表

Occupation table

正如您所看到的,我有一个链接两个表的外键。所以在我的应用程序中,我设置了DataGrid ItemsSource = Employees列表。在我的DataGrid中,我自己定义了列,我禁用了AutoGenerateColumns属性。我有4列,

0:TextColumn

1:TextColumn

2:TextColumn

3:ComboBoxColumn

所以我的问题是,如何将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>

非常感谢您花时间阅读我的问题。附:这都是假数据,所以不要担心屏幕截图中的名称

c# wpf data-binding datagrid datagridcomboboxcolumn
1个回答
1
投票

在您的XAML标记中为DataGridComboBoxColumn元素提供x:Key,然后在事件处理程序中设置其ItemsSource属性:

private void gridMain_Loaded(object sender, RoutedEventArgs e)
{
    employees = EmployeeDataHandler.getAllEmployees();
    List<Occupation> occs = OccupationDataHandler.getAllJobs();
    dgEmployee.ItemsSource = employees;
    cmb.ItemsSource = occs;
}

XAML:

<DataGridComboBoxColumn x:Name="cmb" ClipboardContentBinding="{x:Null}" 
                        Header="Occupation" 
                        SelectedValuePath="ID"
                        SelectedValueBinding="{Binding Occupation}"
                        DisplayMemberPath="Description "/>
© www.soinside.com 2019 - 2024. All rights reserved.