首页 > 解决方案 > 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>

标签: c#wpfcomboboxdatagrid

解决方案


不知道你在做什么,但如果你只是想阅读TextComboBox只需使用发件人伙计!

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();


推荐阅读