Question

I have an MVVM C#/WPF app. I'd like to bind a XamDataGrid to one of my view models, so that users can define how they want their results structure - what column is mapped to what variable.
My core holds such dictionary - Dictionary<string, string>, and I'd like to wrap it in an ObservableCollection and bind to this, rather than copy the data to a DataTable. Problem is, I can't add rows this way (the view seems locked for additions) and changes are not saved. My code:

    <igDP:XamDataGrid
        Grid.Row="1" Grid.Column="0"
        Name="resultStructure"
        DataSource="{Binding VariablesDictionary, Mode=TwoWay}"
        GroupByAreaLocation="None">
        <igDP:XamDataGrid.FieldLayoutSettings>
            <igDP:FieldLayoutSettings 
                AllowFieldMoving="WithinLogicalRow"
                AllowAddNew="True" 
                AllowDelete="True" 
                AddNewRecordLocation="OnBottomFixed" />
        </igDP:XamDataGrid.FieldLayoutSettings>
    </igDP:XamDataGrid>

the view model (relevant part):

private ObservableCollection<DictionaryEntry> variablesDictionary;
        public ObservableCollection<DictionaryEntry> VariablesDictionary
        {
            get { return variablesDictionary; }
            set
            {
                variablesDictionary = value;
                OnPropertyChanged(()=>VariablesDictionary);
            }
        }

...

List<DictionaryEntry> vars = resultStructureModel.Variables.Select(x => new DictionaryEntry {Key = x.Key, Value = x.Value}).ToList();
            VariablesDictionary = new ObservableCollection<DictionaryEntry>(vars);
Was it helpful?

Solution 2

What worked eventually was using a BindingList. ObservableCollection won't let you add rows, but BindingList really provides everything I need.

OTHER TIPS

For adding rows, the XamDataGrid uses either IEditableCollectionView.CanAddnew or IBindingList.AllowNew.

If you use a ListCollectionView for the DataSource of the grid then you can add new rows.

To use the ListCollectionView with an ObservableCollection, pass the ObservableCollection into the ListCollectionView and then use the CollectionView to bind to the grid.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top