Search code examples
c#wpfdictionarymvvmdatagrid

C# WPF ObservableCollection with dictionary inside to MVVM Datagrid


The problem is solved, Insted of using a dictionary I "converted" it to an OS (ObservableCollection) and bound it to a Datagrid inside the DatagridTemplateColumn

I am trying to add my ObservableCollaction which have a property Name and a dictionary with the properties: Name, AvgPrice and Shares.

How do I get the Name, AvgPrice and Shares inside the dictionary to a DataGrid?

The ObservableCollection:

private ObservableCollection<WatchlistModel> _watchlists;
public ObservableCollection<WatchlistModel> Watchlists
{
    get { return _watchlists; }
    set { _watchlists = value; OnPropertyChanged(); }
}

The WatchlistModel

private string _name;
public string Name
{
    get { return _name; }
    set { if(_name != value) { _name = value; OnPropertyChanged(); } }
}

private Dictionary<string, StockModel> _stocks;
public Dictionary<string, StockModel> Stocks
{
    get { return _stocks; }
    set { if (_stocks != value) { _stocks = value; OnPropertyChanged(); } }
}

The Datagrid

<DataGrid AutoGenerateColumns="False" ItemsSource="{Binding Path=Watchlists, UpdateSourceTrigger=PropertyChanged}">
    <DataGrid.Columns>
        <DataGridTextColumn Header="Name" Binding="{Binding Path=Name}" />
        <DataGridTextColumn Header="Average Price" Binding="{Binding Path=AvgPrice}" />
        <DataGridTextColumn Header="Shares" Binding="{Binding Path=Shares}" />
    </DataGrid.Columns>
</DataGrid>

Json format

{
  "name": "My Watchlist",
  "stocks": {
    "Zaptec": {
      "avgPrice": "2,14",
      "name": "Zaptec",
      "shares": 121
    }
  }
}

Solution

  • Use

        <DataGridTemplateColumn>
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
    <!-- Here you can add items control or whatever and bound its ItemSource to your 
    Stocks -->
                </DataTemplate>
            </DataGridTemplateColumn>
        </DataGridTemplateColumn.CellTemplate>
    

    But I don't recommend you to use Dictionary. Make ObservableCollection instead. It's pretty hard to Bind Dictionary<key, val> with observe on Items changed.