Search code examples
c#wpfmvvmwpfdatagrid

Show an empty row when itemssource is null in wpf datagrid


I am working on a project in wpf with mvvm. 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.

Thanks in advance.


Solution

  • You need some kind of ItemsSource that is not null. Just initialize your ObservableCollection<yourType>.

    Easiest is to do it via constructor of your 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). So how should the control itself allow that via UI - there is nothing to store the values in !

    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:

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

    Result: enter image description here