DataGrid: can't edit or add rows.

Apr 10, 2010 at 12:47 PM
Edited Apr 10, 2010 at 12:49 PM

I'm trying to use the WPF Toolkit DataGrid control to edit a Collection of strings, and while the strings display just fine and I can even delete them from the collection via the DataGrid, I can't appear to edit any values or add any new ones, and I can't figure out why this is. Perhaps someone here can help.

My Window has its DataContext set to itself, as follows: 

<Window x:Class="Foo.Bar"
    Title="Foo" Height="506" Width="825" Loaded="Window_Loaded"
    DataContext="{Binding RelativeSource={RelativeSource Self}}">

 Then, further down, there is the datagrid declaration. This binds the ItemsSource property to a dependency property called "StringCollection" of type Collection<string>, and creates one text column with the value bound to the current item in the string collection: 

<wpftoolkit:DataGrid AutoGenerateColumns="False" Name="stringsDataGrid" CanUserAddRows="True" CanUserDeleteRows="True" ItemsSource="{Binding StringCollection}">
                <wpftoolkit:DataGridTextColumn Header="String value" CanUserReorder="True" Binding="{Binding Path=.}" Width="*">

The StringCollection property is declared as a public DependencyProperty in the Window's codebehind as follows:

public Collection<string> StringCollection
    get { return (Collection<string>)GetValue(StringCollectionProperty); }
    set { SetValue(StringCollectionProperty, value); }

// Using a DependencyProperty as the backing store for StringCollection.  This enables animation, styling, binding, etc...
public static readonly DependencyProperty StringCollectionProperty =
    DependencyProperty.Register("StringCollection", typeof(Collection<string>), typeof(Bar), null);

When I run this application, the datagrid displays all the strings in StringCollection perfectly fine, and when I use Delete to remove rows from the datagrid, those strings are automatically removed from StringCollection. So far so good. However, when I edit a row and press Enter to commit the edit, the value in the row just reverts back to the initial value. Also, despite having set the CanUserAddRows property to true, there isn't actually an extra empty row at the bottom of the grid where I could enter a new string.

What exactly am I doing wrong, and how can I set this up in such a way that I can also edit and add new strings to the collection?