找到你要的答案

Q:Force the user to enter data in first cell of the DataGridRow

Q:强制用户在DataGridRow的第一个单元格中输入数据

I have a datagrid. In this datagrid new rows are added programatically.

When a new row is added, the first cell of new row is focused.

Now, if user clicks on any other cell without entering data in the first cell, then focus should not move from first cell. I mean I want the user to enter data in first cell. If he don't want to enter data in first cell, then he/she should press Enter. If he wants to edit any other cell from any other row, then he should be able to do it. But when he again comes to the new row, then he should be forced to focus the first cell

我有一个DataGrid。在DataGrid中添加新行程序。

当添加新行时,新行的第一个单元格将被聚焦。

现在,如果用户单击任何其他单元格而不在第一个单元格中输入数据,则焦点不应该从第一个单元格移动。我的意思是我希望用户在第一个单元格中输入数据。如果他不想在第一个单元格中输入数据,那么他/她应该按回车键。如果他想编辑任何其他单元格从其他行,那么他应该能够做到这一点。但是,当他再次来到新的一排,那么他应该被迫集中的第一个细胞

answer1: 回答1:

Since you don't want focus to move to any other column in the new row, you can disable all the elements of that row.

Now whenever user press an Enter or he/she input some text to the first column of the new row, enable all the elements of that row.

For example, consider the two TextBox. Initially second textbox will be disabled. When user press enter or any data in first TextBox, second TextBox will get enabled.

XAML code:

<TextBox Name="txtBox" Grid.Row="0" KeyDown="txtBox_KeyDown" TextChanged="txtBox_TextChanged"></TextBox>
<TextBox Name="txtBox2" Grid.Row="1" IsEnabled="False"></TextBox>

C# Code:

private void txtBox_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Enter)
        {
            txtBox2.IsEnabled = true;
            txtBox2.Focus();
        }
    }

    private void txtBox_TextChanged(object sender, TextChangedEventArgs e)
    {
        if (!txtBox.Text.Equals(""))
        {
            txtBox2.IsEnabled = true;
        }
        else
        {
            txtBox2.IsEnabled = false;
        }
    }

You can use the same concept to solve your issue.

因为您不希望将焦点移到新行中的任何其他列,因此可以禁用该行的所有元素。

现在,每当用户按Enter或他/她输入新行的第一列时,启用该行的所有元素。

例如,考虑两个文本框。最初的第二文本框将被禁用。当用户按Enter或在第一个文本框的任何数据,第二文本框将启用。

XAML代码:

<TextBox Name="txtBox" Grid.Row="0" KeyDown="txtBox_KeyDown" TextChanged="txtBox_TextChanged"></TextBox>
<TextBox Name="txtBox2" Grid.Row="1" IsEnabled="False"></TextBox>

C #代码:

private void txtBox_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Enter)
        {
            txtBox2.IsEnabled = true;
            txtBox2.Focus();
        }
    }

    private void txtBox_TextChanged(object sender, TextChangedEventArgs e)
    {
        if (!txtBox.Text.Equals(""))
        {
            txtBox2.IsEnabled = true;
        }
        else
        {
            txtBox2.IsEnabled = false;
        }
    }

您可以使用相同的概念来解决您的问题。

c#  wpf  datagrid