Search code examples
c#wpfmvvm-lightwpfdatagrid

Adding rows in datagrid not working as expected mvvm light


I am using mvvm Light and what I want is to add/delete some rows in my datagrid. The initial values are displayed, but when I add some info my collection is populated with the values I entered, but its type is GalaSoft.MvvmLight.ObservableObject and not "MyType" and because of this when I want to delete a new added row my application craches (SelectedItem is null)...(if I want to delete a row that was not added manually it works!).

<DataGrid Name="Table" ItemsSource="{Binding MyCollection}" SelectedItem="{Binding SelectedItem}" IsSynchronizedWithCurrentItem="True">
            <DataGrid.Columns>
                <DataGridTextColumn Header="ID" Width="*" Binding="{Binding Path=Id,Mode=TwoWay}"  />
                <DataGridTextColumn Header="Name" Width="*" Binding="{Binding Path=Name,Mode=TwoWay}" />
    </DataGrid.Columns>

in viewModel:

public MyType SelectedItem
{
  get { return _selectedItem; }
  set
  {
    _selectedItem = value;
    RaisePropertyChanged();
  }
}  
public ObservableCollection<ObservableObject> MyCollection
{
  get
  {
    return _myCollection;
  }
  set
  {
    _myCollection = value;
    RaisePropertyChanged();
  }
}  
public RelayCommand RemoveRow { get { return new RelayCommand(RemoveRowCommand, CanRemove); } }
public RelayCommand AddRow { get { return new RelayCommand(AddRowCommand, CanAdd); } }  

public void RemoveRowCommand()
{
  MyCollection.Remove(SelectedItem);
}

public void AddRowCommand()
{
  MyCollection.Add(SelectedItem);
}

Solution

  • Make your class inherit BindableBase. Make property lik this

    private ObservableColletion<ObservableObject> _myCollection;
    public ObservableCollection<ObservableObject> MyCollection
    {
      get
      {
        return _myCollection;
      }
      set
      {
        SetProperty(ref _myCollection,new ObservableCollection<ObservableObject>(value));
      }
    } 
    

    SetProperty method (from BindableBase class) takes care about raising property change events. It should works :)