[英]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.