Editable DataGrid - CanUserAddRows=“True” not working

六月ゝ 毕业季﹏ 提交于 2019-11-29 12:03:54
yu yang Jian

In my case,

First ensure your ItemSource is not using an array that can't add new item to it,

use something like List that can add newItem,

Besides, the List Class should have an default constructor takes no parameters like

List<SomeClass>();

public Class SomeClass{

  public SomeClass(){}

}

then the new empty row appear in the bottom of the datagrid.

refernce to this answer https://stackoverflow.com/a/21089367/4573839

I'm going ahead and posting this as an answer here as I need to post a code sample and the comments are starting to become extended (got the invite-to-chat message).

The answer to the original question was ensure that the Type T of the ItemsSource had a parameterless constructor.

Try this code attached to the DataGrid's BeginningEdit event to swallow up the cell border clicks:

private void Grid_BeginningEdit(object sender, DataGridBeginningEditEventArgs e)
{
    //// Have to do this in the unusual case where the border of the cell gets selected
    e.Cancel = true;
}

If you are actually using this handler for something else, or intend to, you can check the OriginalSource to see if it is a Border and cancel the event on that condition.

Use DataGridTextColumn and DataGridComboBoxColumn instead DataGridTemplateColumn, then rows will be added by adequately.

If you want to use DataGridTemplateColumn, then set not only the CellTemplate, but CellEditingTemplate. For example:

<DataGridTemplateColumn Header="Pick a Date">
<DataGridTemplateColumn.CellTemplate>
    <DataTemplate>
        <TextBlock Text="{Binding myDate}" />
    </DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
    <DataTemplate>
        <DatePicker SelectedDate="{Binding myDate}" />
    </DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!