如何以正确的方式从DataGrid中的ComboBox获取SelectionChanged事件?

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

我有模特

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,我使用GridItemsObservableCollection的每个元素实际上是在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>
...

有屏幕截图

enter image description here

现在,当用户在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
1个回答
2
投票

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

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

或者只是摆脱事件处理程序,并在SelectedGeoCalibrationFolder的设置方法中处理您的逻辑。这就是使用MVVM解决此问题的方式。

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.