WPF DataGrid cannot Add a row when datasource is empty

久未见 提交于 2019-12-04 03:04:03

问题


CanUserAddRows="True" only 'works' when there's already data in the ItemsSource of the DataGrid. If it just so happens that there are no rows in the original list of items, then the DataGrid doesn't display a placeholder row for entering new items, even though I've set CanUserAddRows="True". Why?!

Thanks in advance, Trindaz


回答1:


This seem to be a known issue with WPF DataGrid. See discussion here (starting from the 4th comment) Also it seem to be fixed in .net 4. I've made some tests for this issue on 3.5 and 4 (beta2) frameworks. Pls, see results below:

First I defined 3 types of item collections:

public class TestGridItems0 : ArrayList
{
}

public class TestGridItems1 : List<TestGridItem>
{
}

public class TestGridItems2<T> : List<TestGridItem>
{
}

where TestGridItem is below:

public class TestGridItem
{
    public string One { get; set; }
    public string Two { get; set; }
    public string Three { get; set; }
}

.net 3.5

TestGridItems0 and TestGridItems1 didn't show an empty line for an empty collection; where as TestGridItems2 did work fine.

.net 4

only TestGridItems0 didn't show the line for the empty collection; other 2 worked fine.

xaml for the grid:

<my:DataGrid Name="dataGrid" AutoGenerateColumns="False" CanUserAddRows="True">
    <my:DataGrid.Columns>
        <my:DataGridTextColumn Binding="{Binding One}" Header="One" />
        <my:DataGridTextColumn Binding="{Binding Two}" Header="Two" />
        <my:DataGridTextColumn Binding="{Binding Three}" Header="Three" />
    </my:DataGrid.Columns>
</my:DataGrid>

below is how items source was assigned:

dataGrid.ItemsSource = new TestGridItems0();
dataGrid.ItemsSource = new TestGridItems1();
dataGrid.ItemsSource = new TestGridItems2<TestGridItem>();

hope this helps, regards




回答2:


Add an empty item to your ItemsSource and then remove it. You may have to set CanUserAddRows back to true after doing this. I read this solution here: (Posts by Jarrey and Rick Roen)

I had this problem when I set the ItemsSource to a DataTable's DefaultView and the view was empty. The columns were defined though so it should have been able to get them. Heh.



来源:https://stackoverflow.com/questions/2075644/wpf-datagrid-cannot-add-a-row-when-datasource-is-empty

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