1
votes

I have a datagrid with 2 columns, no initial data, and I need to make the user to be able to add columns as he wants.

What I did is adding a DataGrid, a button for adding a row, and a class which represents the row:

Xaml:

        <DataGrid AutoGenerateColumns="False" Height="51" HorizontalAlignment="Left" Margin="374,354,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="204" CanUserAddRows="True" AreRowDetailsFrozen="False" CanUserDeleteRows="True" ItemsSource="{Binding FilterBinding}">
        <DataGrid.Columns>
            <DataGridTextColumn Header="Key" IsReadOnly="False" Binding="{Binding Key}" ></DataGridTextColumn>
            <DataGridTextColumn Header="Value" IsReadOnly="False" Binding="{Binding Value}" ></DataGridTextColumn>
        </DataGrid.Columns>
    </DataGrid>
    <Button Content="Add" Height="23" HorizontalAlignment="Left" Margin="503,330,0,0" Name="button5" VerticalAlignment="Top" Width="75" Click="button5_Click" />

MainWindow.xaml.cs:

private void button5_Click(object sender, RoutedEventArgs e)
    {
        var data = new FilterItem { key = "Key", value = "Value" };
        dataGrid1.Items.Add(data);
    }

FilterItem.cs:

public class FilterItem
{
    public string key { get; set; }
    public string value { get; set; }
}

The problem is that the rows that are added are not editable and a double click on a cell throws the exception:

'EditItem' is not allowed for this view. (InvalidOperationException was unhandled)

What did I do wrong?

1

1 Answers

0
votes

I guess it's because the property to access the collection object is read-only. See here for information: MSDN: ItemsControl.Items Property.

I would create a store for the items:

private ObservableCollection<FilterItem> _data = new ObservableCollection<FilterItem>();

public ObservableCollection<FilterItem> Data
{
  get { return _data; }
}

Now you bind your DataGrid to this store, for example:

<DataGrid ... ItemsSource="{Binding Data, ElementName=window}">

And finally your button:

_data.Add(new FilterItem());

With that you create a store in your window and bind the DataGrid to this store. Every time you change the item collection, the DataGrid show the new values and you can change the items.

I suggest to implement INotifyPropertyChanged for your FilterItem. With that, every time you change the item, the DataGrid is notified.