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

C# 如何以正确的方式从DataGrid中的ComboBox获取SelectionChanged事件?,c#,wpf,C#,Wpf,我有一个模型 public class UCClipProcessingModel : BaseModel { public ObservableCollection<ClipProcessingGridItem> GridItems { get; } = new ObservableCollection<ClipProcessingGridItem>(); } 有一个截图 现在我需要知道当用户在组合框中更改值时,我能做什么才能得到它?

我有一个模型

public class UCClipProcessingModel : BaseModel
{
    public ObservableCollection<ClipProcessingGridItem> GridItems { get; }
            = new ObservableCollection<ClipProcessingGridItem>();
}
有一个截图

现在我需要知道当用户在组合框中更改值时,我能做什么才能得到它?我设置了
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
中的
observateCollection
关联


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

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

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

或者干脆去掉事件处理程序,在
SelectedGeoCalibrationFolder
的setter中处理逻辑。这就是使用MVVM解决此问题的方法。

您可以给出一个如何使用MVVM的示例吗?@AlekseyTimoshchenko:只需将调用移动到
控制台。在您的示例中,将WriteLine
移动到绑定到
SelectedEdItem
属性的
SelectedGeoCalibrationFolder
源属性的setter。但是如果你有其他问题,请问一个新问题。
private void Cb_geometry_calibration_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    if (((sender as ComboBox).SelectedItem) is MCGeoCalibFolder itemm)
    {
        Console.WriteLine($"Item clicked: {itemm.ToString()}");
    }
}
var comboBox = sender as ComboBox;
var item = comboBox.DataContext as ClipProcessingGridItem;