【问题标题】:Blank Row missing when DataGrid has no dataDataGrid 没有数据时缺少空白行
【发布时间】:2012-05-24 21:32:48
【问题描述】:

我正在开发 WPF,我正在设计一个包含数据网格的控件,到目前为止一切顺利。

但是刚刚发生了一些奇怪的事情:如果我在数据网格中显示一行或多行,数据网格最后会显示用于添加新行的空白行,正常情况下,但是如果数据网格中没有行,空白行也没有显示!。

所以,我需要我的数据网格始终在末尾有一个空白行,无论是否有数据。

我已尝试使用属性 CanUserAddRowsIsReadOnly,但正如我之前所说,它仅在有一行或多行时才有效。

有人知道如何实现吗?

提前谢谢你。

【问题讨论】:

    标签: wpf datagrid


    【解决方案1】:

    你的意思是空行吗?看看wpf datagrid blank row missing上的答案

    这个基本设置确实会显示一个空白行(即使绑定的 ItemsSource 没有数据)

    XAML

    <Window x:Class="Demo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525"
        DataContext="{Binding RelativeSource={RelativeSource Self}}"
        >
    <Grid>
        <DataGrid ItemsSource="{Binding Items}">
            <!--Must define columns if you need columns before bound collection has data-->
            <DataGrid.Columns>
                <DataGridTextColumn Header="Property"  Binding="{Binding Path=MyProperty}">   </DataGridTextColumn>
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
    </Window>
    

    后面的代码

    public class Data
    {
        public Data(string value) { MyProperty = value; }
        public Data() { }  // Must have default constructor
        public String MyProperty { get; set; }
    }
    
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {        
        List<Data> _items = new List<Data>(); 
        public List<Data> Items
        {
            get { return _items; }
        }
    
        public MainWindow()
        {
            InitializeComponent();
       }
    

    【讨论】:

    • 其实我看过那篇文章,但对我没用,我仍然有同样奇怪的问题
    • @Dante 数据网格绑定到什么?你能发布足够的代码来重现问题吗?
    • 现在我正在从 DataTable 中检索数据,我所做的是:MyDataGrid.ItemsSource = myDataTable.DefaultView
    • 我已经尝试过你的代码,但我仍然遇到同样的奇怪行为:(
    • @Dante - 添加您在 XAML 中定义 DataGrid 列?