简体   繁体   English

如何从DataGrid WPF中的ComboBox列获取SelectedItem属性

[英]How to get the SelectedItem property from a ComboBox column in a DataGrid wpf

recently we started to use WPF at work. 最近,我们开始在工作中使用WPF。 Now I want to create a DataGrid from a list of objects (DataGrid ItemSource) that contains a project role, the employee that should do the job and a list of employees that could also do that job. 现在,我想从包含项目角色的对象列表(DataGrid ItemSource),应该执行此工作的员工以及也可以执行该工作的员工列表中创建一个DataGrid。 Lets call this list the "MainList". 让我们将此列表称为“ MainList”。 In that DataGrid is a ComboBox Column that uses another list of objects as ItemSource where you can change the employee for the job. 在该DataGrid中,是一个ComboBox列,该列使用另一个对象列表作为ItemSource,您可以在其中更改作业的员工。 I will call this list the "ChildList". 我将此列表称为“ ChildList”。 This list is included in the MainList (as allready mentioned) and I bind it by using the correct BindingPath. 该列表包含在MainList中(正如已经提到的那样),我通过使用正确的BindingPath对其进行绑定。 So far so good. 到现在为止还挺好。 Now I have to set the SelectedItem (to show which Employee is currently selected). 现在,我必须设置SelectedItem(以显示当前被选中的Employee)。 From the MainList I can get the employee that should be selected from the ChildList. 从MainList中,我可以获得应该从ChildList中选择的雇员。 Obviously I cant do this by Binding. 显然我不能通过绑定来做到这一点。 Unfortunatly I cant get the SelectedItem property in the code-behind. 不幸的是,我无法在后面的代码中获取SelectedItem属性。 Basically I need to go through every row from the DataGrid and get the Item that should be selected in the ComboBox. 基本上,我需要遍历DataGrid的每一行并获取应在ComboBox中选择的Item。 Then I would go through the ComboBox Items until I find the matching Item and set this as SelectedItem. 然后,我将遍历ComboBox项目,直到找到匹配的项目并将其设置为SelectedItem。 But I cant find a way to do this. 但是我找不到办法。

I tried using a DataGridComboBoxColumn aswell but it has only the SelectedItemBinding property and since you cant compare while binding this should not work. 我也尝试使用DataGridComboBoxColumn,但它仅具有SelectedItemBinding属性,并且由于无法在绑定时进行比较,因此这不起作用。 I also tried to get every cell in the code-behind, that is a ComboBox but without success so far. 我还尝试使代码中的每个单元格都隐藏在一个ComboBox中,但到目前为止没有成功。

<DataGrid x:Name="DgvProjectTeam" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" AutoGenerateColumns="False" Margin="0" RowHeight="40" CanUserAddRows="False" BorderThickness="1" VerticalScrollBarVisibility="Auto" HorizontalGridLinesBrush="#FFA2B5CD" VerticalGridLinesBrush="#FFA2B5CD" ItemsSource="{Binding}" VirtualizingStackPanel.IsVirtualizing="False">
  <DataGrid.Columns>
      <DataGridTemplateColumn Header="Resource" Width="200" x:Name="DgtProjectCoreTeam">
           <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                      <ComboBox Name="CbxResource" ItemsSource="{Binding Path=ListOfPossibleResources}" DisplayMemberPath="ResourceOfQMatrix.Fullname"/>
                 </DataTemplate>
           </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>

The DataGrid shows everything I need. DataGrid显示了我需要的一切。 I just dont know how I can set the SelectedItem for each of the generated ComboBoxCells in the code-behind. 我只是不知道如何在后面的代码中为每个生成的ComboBoxCells设置SelectedItem。

Anyone an idea? 有人知道吗?

Here's a quick example of what you can do. 这是您可以做什么的简单示例。 First, define your view models that will be bound to the DataGrid . 首先,定义将绑定到DataGrid视图模型。 Ideally, these view models would raise PropertyChanged or CollectionChanged when their properties are changed, but for this simple example this is not needed. 理想情况下,这些视图模型在更改其属性时会引发PropertyChangedCollectionChanged ,但是对于此简单示例,则不需要这样做。

public class ViewModel
{
    public List<ProjectRoleViewModel> ProjectRoles { get; set; }
}

public class ProjectRoleViewModel
{
    public string Role { get; set; }
    public string Employee { get; set; }
    public List<string> OtherEmployees { get; set; }
    public string SelectedOtherEmployee { get; set; }
}

I've hard-coded some dummy values to have data in the view models: 我已经将一些虚拟值硬编码为视图模型中的数据:

var viewModel = new ViewModel
{
    ProjectRoles = new List<ProjectRoleViewModel>
    {
        new ProjectRoleViewModel
        {
            Role = "Designer",
            Employee = "John Smith",
            OtherEmployees = new List<string> {"Monica Thompson", "Robert Gavin"}
        },
        new ProjectRoleViewModel
        {
            Role = "Developer",
            Employee = "Tom Barr",
            OtherEmployees = new List<string> {"Jason Ross", "James Moore"}
        }
    }
};

This view model then needs to be assigned to the DataContext of your Window or UserControl that contains the DataGrid . 然后需要将此视图模型分配给包含DataGrid WindowUserControlDataContext Here's the XAML for the DataGrid : 这是DataGrid的XAML:

<DataGrid
    ItemsSource="{Binding ProjectRoles}"
    AutoGenerateColumns="False"
    >
    <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding Role}" />
        <DataGridTextColumn Binding="{Binding Employee}" />
        <DataGridTemplateColumn>
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <ComboBox
                        ItemsSource="{Binding OtherEmployees}"
                        SelectedItem="{Binding SelectedOtherEmployee, UpdateSourceTrigger=PropertyChanged}"
                        />
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

After the user picks the "other" employee that can do the job, the view model's SelectedOtherEmployee will have the chosen value. 用户选择可以完成工作的“其他”员工之后,视图模型的SelectedOtherEmployee将具有选定的值。 You don't need any code-behind in this case, everything's contained in the view models. 在这种情况下,您不需要任何代码,所有内容都包含在视图模型中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM