[英]C# WPF ListView MVVM ObservableCollection inside of an ObservableCollection
[英]C# WPF ObservableCollection with dictionary inside to MVVM Datagrid
問題解決了,使用字典我將其“轉換”為操作系統(ObservableCollection)並將其綁定到 DatagridTemplateColumn 內的 Datagrid
我正在嘗試添加我的 ObservableColaction ,它有一個屬性Name
和一個具有屬性的字典: Name
, AvgPrice
和Shares
。
如何將字典中的Name
、 AvgPrice
和Shares
獲取到DataGrid ?
ObservableCollection:
private ObservableCollection<WatchlistModel> _watchlists;
public ObservableCollection<WatchlistModel> Watchlists
{
get { return _watchlists; }
set { _watchlists = value; OnPropertyChanged(); }
}
觀察名單模型
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(); } }
}
數據網格
<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 格式
{
"name": "My Watchlist",
"stocks": {
"Zaptec": {
"avgPrice": "2,14",
"name": "Zaptec",
"shares": 121
}
}
}
利用
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<!-- Here you can add items control or whatever and bound its ItemSource to your
Stocks -->
</DataTemplate>
</DataGridTemplateColumn>
</DataGridTemplateColumn.CellTemplate>
但我不建議你使用字典。 改為使用 ObservableCollection。 將 Dictionary<key, val> 綁定到對 Items 更改的觀察是非常困難的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.