C#WPF DataGrid可编辑组合框通过单击编辑将-1返回为选中行
我试图从DataGrid表中的可编辑组合框中获取单元格值。当从选项中选择项目时,成功/正确地提取值,但当用户在组合框中输入文本时,则不会成功/正确提取值(除非双击) 问题:行索引变为-1(在单击文本条目时),就好像未选择行一样,导致代码失败,并错误地处理更新。 我怎样才能解决这个问题?如果强制用户双击是一个有效的选项,我该怎么做 这是我的C#代码:C#WPF DataGrid可编辑组合框通过单击编辑将-1返回为选中行,c#,wpf,combobox,datagrid,C#,Wpf,Combobox,Datagrid,我试图从DataGrid表中的可编辑组合框中获取单元格值。当从选项中选择项目时,成功/正确地提取值,但当用户在组合框中输入文本时,则不会成功/正确提取值(除非双击) 问题:行索引变为-1(在单击文本条目时),就好像未选择行一样,导致代码失败,并错误地处理更新。 我怎样才能解决这个问题?如果强制用户双击是一个有效的选项,我该怎么做 这是我的C#代码: private void组合框\u LostFocus(对象发送方,RoutedEventArgs e) { 如果(e!=null) { 文本框t=
private void组合框\u LostFocus(对象发送方,RoutedEventArgs e)
{
如果(e!=null)
{
文本框t=e。源为文本框;
如果(t!=null)
{
尝试
{
int RowIndex=MYGRID.Items.IndexOf(MYGRID.SelectedItem);
如果(行索引<0)
{
MessageBox.Show(“Index<0”);//用于测试
}
//获得新的价值
字符串值=t.Text.ToString();
//获取项目ID
DataGridRow Row=(DataGridRow)MYGRID.ItemContainerGenerator.ContainerFromIndex(RowIndex);
DataGridCell RowColumn=MYGRID.Columns[0]。GetCellContent(行)。父级为DataGridCell;
int ID=Convert.ToInt32(((TextBlock)RowColumn.Content.Text);
//无关代码继续。。。
}
捕获(异常){}
}
}
}
以下是我对该列的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>
不确定你在做什么,但是如果你只是想阅读
组合框的文本,就用发送者都德
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);
}
公共静态DependencyObject GetParent(DependencyObject子对象)
{
if(child==null)返回null;
var parent=visualtreeheloper.GetParent(子级);
返回父项为T?父项:GetParent(父项);
}
用法:
var index=((DataGridRow)GetParent(comboBox))?.GetIndex()代码>我刚刚测试了您的案例,我可以确认没有设置网格上的选定项目。您是否尝试过使用VisualTreeHelper
获取DataGridRow
的父类型?我该怎么做?googlewpf find parent
,您将找到一个针对特定父类型的递归搜索,一旦找到它,然后设置所选属性。然后绑定将启动,网格中选定项的属性将具有当前选定项。我刚刚尝试实现该方法,但TryParse在单击一次时失败,而在双击时失败可能是因为组合框文本不是整数值!我可以通过执行value=comboBox.Text获得字符串值;在这种情况下,有没有办法获取当前行的整数值?我仍然需要行索引从其他列中获取其他值。好了,我们就到了!我现在需要获取同一行中两个不同列中的值,但我以前使用的方法是将索引用作DataGridRow对象,不再有效,因为它没有引用相同的对象。不确定您的意思是什么,但如果您使用的是DaraGridRow
befire,您可以使用与以前相同的方法,而不会出现任何问题。
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);
}