简体   繁体   中英

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
    }
  }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM