c# - 如何以正确的方式从 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
......
问题是 -如何知道与哪个元素关联的更改值?
解决方案
您可以将DataContext
数据项转换为任何类型:
var comboBox = sender as ComboBox;
var item = comboBox.DataContext as ClipProcessingGridItem;
或者干脆摆脱事件处理程序并在SelectedGeoCalibrationFolder
. 这就是使用 MVVM 解决这个问题的方法。
推荐阅读
- c++ - 字符串转换为 const char*
- node.js - 使用 NodeJS 在 MongoDB 中进行大数据处理和管理
- c# - 为 Builder 类编写单元测试
- java - 谷歌地图标记自定义信息从 Firebase 获取数据
- sql-server - 如何仅允许与特定公共 IP 地址(白名单)的 SQL Server 实例进行远程连接并限制对所有其他 IP 的访问
- r - 无法使用 grVizOutput() 和 renderGrViz() 运行闪亮的应用程序
- c++ - std::visit 和 std::variant 用法
- bigdata - 如何监控 Flink 应用程序?
- node.js - 是否有任何自定义库可以在nodejs中生成相当于mysql表的实体
- reactjs - 无法使用 okta react login 创建嵌套路由