title: How to Add a New Row to DataGrid in MVVM Friendly Way
body: <p>I have the following <code>DataGrid</code></p>
  
  <pre><code>&lt;DataGrid CanUserDeleteRows="True" 
            CanUserAddRows="True"
            SelectedItem="{Binding SelectedResource, Mode=TwoWay}"
            ItemsSource="{Binding Path=Resources, Mode=TwoWay,
                                  UpdateSourceTrigger=PropertyChanged, 
                                  IsAsync=True}"&gt; ... &lt;/&lt;DataGrid&gt;
  </code></pre>
  
  <p>I am using the MVVM pattern to bind to an <code>ObservableCollection&lt;ResourceViewModel&gt; Resources</code> and this works great. I have a button that adds a new row and this is done by adding a new <code>ResourceViewModel</code> to the <code>Resources</code> collection - great. Now, I want the user to be able to click on the empty last row, and this automatically creates a new record in the <code>DataGrid</code>.</p>
  
  <p>I have made sure the <code>DataGrid</code> has <code>CanUserAddRows=True</code>. I have made sure the class in the collection <code>Resources</code> (<code>ResourceViewModel</code>) that I am binding to has a default constructor (no parameters) and I have made sure the collection type is not readonly. When the user clicks on the last row the default constructor fires but to correctly instantiate the new <code>ResourceViewModel</code> object in need a reference to either the grid of the <code>Resources</code> collection... </p>
  
  <p>I suppose I could use and <code>AttachedCommand</code> on the <code>CellBeginEdit</code> event and then add a new <code>ResourceViewModel</code> to the observable collection there, <strong>is there a standard way of doing this?</strong></p>
  
  <hr>
  
  <p>Note, I have read the following questions and these are of no help to me</p>
  
  <ol>
  <li><a href="https://stackoverflow.com/questions/4617810/wpf-datagrid-event-for-new-rows">WPF DataGrid - Event for New Rows?</a></li>
  <li><a href="https://stackoverflow.com/questions/8556809/how-to-add-rows-with-a-datagrid-and-mvvm">How to add rows with a DataGrid and MVVM</a></li>
  </ol>
  
  <hr>
  
  <p>Edit. It turns out that I am having problems doing this due to a bug in the WPF <code>DataGrid</code>. See <a href="http://blog.spencen.com/2009/04/30/problems-binding-to-selectedvalue-with-microsoftrsquos-wpf-datagrid.aspx?view=threaded#Comment" rel="nofollow noreferrer">Nigel Spencer's Blog</a>. However, his fix is not working for me at the moment...</p>