c# - C# WPF DataGrid 可编辑组合框返回 -1 作为单击编辑的选定行
问题描述
我正在尝试从 DataGrid 表中的可编辑组合框中获取单元格值。从选项中选择项目时成功/正确提取值,但当用户在组合框中输入文本时不会(除非他们双击)
问题:RowIndex 变为 -1(在单击文本条目时),好像没有选择一行,导致代码失败,并错误地处理更新。
我怎样才能解决这个问题?如果强制用户双击是一个有效的选项,我该怎么做?
这是我的 C# 代码:
private void ComboBox_LostFocus(object sender, RoutedEventArgs e)
{
if (e != null)
{
TextBox t = e.Source as TextBox;
if (t != null)
{
try
{
int RowIndex = MYGRID.Items.IndexOf(MYGRID.SelectedItem);
if (RowIndex < 0)
{
MessageBox.Show("Index < 0"); //For Testing
}
//Obtain new Value
string Value = t.Text.ToString();
//Obtain item ID
DataGridRow Row = (DataGridRow)MYGRID.ItemContainerGenerator.ContainerFromIndex(RowIndex);
DataGridCell RowColumn = MYGRID.Columns[0].GetCellContent(Row).Parent as DataGridCell;
int ID = Convert.ToInt32(((TextBlock)RowColumn.Content).Text);
//Unrelated code continues...
}
catch (Exception) { }
}
}
}
这是我的列的 XAML 代码:
<DataGridTemplateColumn x:Name="ValueCol" Header="Value">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox ItemsSource="{Binding Options, UpdateSourceTrigger=PropertyChanged}" SelectedItem="{Binding Path=UpdatedData, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, NotifyOnTargetUpdated=True}" IsEditable="True" LostFocus="ComboBox_LostFocus" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
解决方案
不知道你在做什么,但如果你只是想阅读Text
,ComboBox
只需使用发件人伙计!
private void ComboBox_LostFocus(Object sender, RoutedEventArgs e)
{
var comboBox = sender as ComboBox;
if (comboBox != null)
{
int id;
if(int.TryParse(comboBox.Text, out id))
{
// do your thing!!!!
}
}
}
要获取索引,您可以使用以下辅助方法:
public static DependencyObject GetParent<T>(DependencyObject child)
{
if (child == null) return null;
var parent = VisualTreeHelper.GetParent(child);
return parent is T ? parent : GetParent<T>(parent);
}
用法:
var index = ((DataGridRow)GetParent<DataGridRow>(comboBox))?.GetIndex();
推荐阅读
- android - android/view/view$onUnhandledKeyEventListener (onMeasure 错误)
- c - Mac OS X中C变量的奇怪地址
- ruby-on-rails - 缺少 RSpec 测试方法
- javascript - ASP.NET MVC 5 网站中的 CSS 和 Javascript 以及图像在部署后不会显示
- ruby-on-rails - ActionMailer 在带有附件的邮件中重复正文
- docker - 如何在另一个用作反向代理的容器 Nginx 后面为 Drupal 8 配置带有 Apache 的容器
- sql - 当子表中存在多个指向同一列的外键时,如何获取父表相同的数据?
- c - 除了最后一个之外,所有#pragma GCC 诊断都被忽略
- ios - 当任务太短时,加载覆盖会导致问题
- codeigniter - 发送邮件时将html转换为pdf