简体   繁体   English

在wpf datagrid中itemssource为null时显示空行

[英]Show an empty row when itemssource is null in wpf datagrid

I am working on a project in wpf with mvvm. 我正在使用mvvm在wpf中进行项目。 I just want to show a row on a wpf datagrid to add a new item and i have an ItemsSource but it is null and canUserAddRows is set to true. 我只想在wpf数据网格上显示一行以添加一个新项目,并且我有一个ItemsSource但它为nullcanUserAddRows设置为true。

Thanks in advance. 提前致谢。

You need some kind of ItemsSource that is not null . 您需要某种not nullItemsSource Just initialize your ObservableCollection<yourType> . 只需初始化您的ObservableCollection<yourType>

Easiest is to do it via constructor of your ViewModel: 最简单的方法是通过ViewModel的构造函数来实现:

public class ViewModel : INotifyPropertyChanged
{
     public ViewModel()
     {
          _yourCollection = new ObservableCollection<yourType>();
          //Now Items can be added, via code behind, or UI !
     }
}

Think of it : You cannot call .Add() on a null object (would throw NullReferenceException ). 想一想 :您不能在null对象上调用.Add() (将抛出NullReferenceException )。 So how should the control itself allow that via UI - there is nothing to store the values in ! 因此,控件本身应如何通过UI允许它-没有值可存储在!

Example: 例:

ViewModel: 视图模型:

public class ViewModel 
{

     public ObservableCollection<Model> Collection { get; set;}         

     public ViewModel()
     {
          Collection = new ObservableCollection<Model>();
          //Now Items can be added, via code behind, or UI !
     }
}

Model: 模型:

public class Model
{
    public string Text { get; set; }
}

Xaml: XAML:

<DataGrid CanUserAddRows="True"
          AutoGenerateColumns="False"
          IsReadOnly="False"
          ItemsSource="{Binding Collection}">
    <DataGrid.Columns>
        <DataGridTextColumn Width="*" 
                            Header="Value" 
                            Binding="{Binding Text}"/>
    </DataGrid.Columns>
</DataGrid>

Result: 结果: 在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM