WPF中使用ItemContainerGenerator.ContainerFromItem高亮DataGrid行时出现多行被错误高亮的问题求助
WPF中使用ItemContainerGenerator.ContainerFromItem高亮DataGrid行时出现多行被错误高亮的问题求助
我遇到一个挺棘手的问题,是关于WPF里这段C#代码的:
DataGridRow row = (DataGridRow)AllLinesData.ItemContainerGenerator.ContainerFromItem(AllLinesData.SelectedItem)
我本来想用这段代码来高亮DataGrid里选中的行,但实际运行起来,它不光高亮了选中的行,还会随机高亮其他没选中的行。
下面是我用到的相关代码:
private void cellTextBox_KeyDown(object sender, KeyEventArgs e) { if (AllLinesData.SelectedItem != null) { DataGridRow row = (DataGridRow)AllLinesData.ItemContainerGenerator.ContainerFromItem(AllLinesData.SelectedItem); if (row != null) { rowNotes[row] = cellTextBox.Text; // 保存对应行的文本 SolidColorBrush BrushColor = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#3393378B")); row.Background = BrushColor; } } } private async void AllLinesData_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (AllLinesData.SelectedItem != null) { // 获取选中的行 DataGridRow row = (DataGridRow)AllLinesData.ItemContainerGenerator.ContainerFromItem(AllLinesData.SelectedItem); // 确保该行不在编辑模式,且数据上下文是目标对象 if (row != null && !row.IsEditing && row.DataContext is TextData) { cellTextBox.Text = rowNotes.ContainsKey(row) ? rowNotes[row] : ""; // 获取光标位置 Point cursorPosition = Mouse.GetPosition(this); cellTextBox.Visibility = Visibility.Visible; cellTextBox.Opacity = 0; // 设置TextBox初始位置 Canvas.SetLeft(cellTextBox, cursorPosition.X - 100); Canvas.SetTop(cellTextBox, cursorPosition.Y); // 启动显示动画 DoubleAnimation opacityAnimation = new DoubleAnimation { From = 0, To = 1, Duration = TimeSpan.FromSeconds(0.3) // 动画时长 }; cellTextBox.BeginAnimation(OpacityProperty, opacityAnimation); // 等待动画完成(按需) await Task.Delay(TimeSpan.FromSeconds(0.3)); } } }
实际的错误效果如下:
- (未选中) Item1 - Good Square (颜色为白色,正常)
- (已选中) Item2 - Square (颜色为红色,符合预期)
- (未选中) Item3 - System (也变成了红色,但我根本没选中它)
我试过调整这个方法,但目前这个逻辑是最贴合我的业务需求的,有没有大佬能告诉我该怎么解决这个问题?
附上程序的截图:
备注:内容来源于stack exchange,提问作者Light Mirto
相关产品推荐
相关产品推荐

