首页 > 解决方案 > 如何以正确的方式从 DataGrid 中的 ComboBox 获取 SelectionChanged 事件?

问题描述

我有一个模型

public class UCClipProcessingModel : BaseModel
{
    public ObservableCollection<ClipProcessingGridItem> GridItems { get; }
            = new ObservableCollection<ClipProcessingGridItem>();
}

并且有一个项目

public class ClipProcessingGridItem: IValidable
{
    public MCClipFolder ClipFolder { get; set; }

    public MCGeoCalibFolder SelectedGeoCalibrationFolder { get; set; } = MCGeoCalibFolder.EMPTY();

    public ObservableCollection<MCGeoCalibFolder> GeoCalibrationFolders { get; set; }
            = new ObservableCollection<MCGeoCalibFolder>();

    public MCColorCalibFolder SelectedColorCalibrationFolder { get; set; } = MCColorCalibFolder.EMPTY();

    public ObservableCollection<MCColorCalibFolder> ColorCalibrationFolders { get; set; }
            = new ObservableCollection<MCColorCalibFolder>();

    public bool IsValid()
    {
        return true;
    }
}

因此,在我.xalm使用的上下文中UCClipProcessingModel,对于我来说,DataGrid我使用它的GridItems每个元素,ObservableCollection它实际上是我的DataGrid.

现在,在我的行中,我有一个这样的DataGridTemplateColumn

...
<DataGridTemplateColumn Header="Geometry calibration folder">
  <DataGridTemplateColumn.CellTemplate>
    <DataTemplate>
      <ComboBox x:Name="Cb_geometry_calibration"
                SelectionChanged="Cb_geometry_calibration_SelectionChanged"
                ItemsSource="{Binding Path=GeoCalibrationFolders}"
                SelectedItem="{Binding Path=SelectedGeoCalibrationFolder}">
        <ComboBox.ItemTemplate>
          <DataTemplate>
            <TextBlock Text="{Binding Path=UIRepresentation}" />
          </DataTemplate>
        </ComboBox.ItemTemplate>
      </ComboBox>
    </DataTemplate>
  </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
...

有截图

在此处输入图像描述

现在我需要知道用户更改它时的价值ComboBox,我该怎么做才能得到它?我设置SelectionChanged方法

private void Cb_geometry_calibration_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    if (((sender as ComboBox).SelectedItem) is MCGeoCalibFolder itemm)
    {
        Console.WriteLine($"Item clicked: {itemm.ToString()}");
    }
}

一切都很好,我可以得到改变的价值,但问题是我不知道这个价值与哪个ClipProcessingGridItem相关ObservableCollection......

问题是 -如何知道与哪个元素关联的更改值?

标签: c#wpf

解决方案


您可以将DataContext数据项转换为任何类型:

var comboBox = sender as ComboBox;
var item = comboBox.DataContext as ClipProcessingGridItem;

或者干脆摆脱事件处理程序并在SelectedGeoCalibrationFolder. 这就是使用 MVVM 解决这个问题的方法。


推荐阅读