c# - 如何绑定 SortedDictionary> 使用 Listbox、MVVM 模式存储?
问题描述
我是 C# 上的新手 MVVM 模式。我正在尝试使用 MVVM 模式将变量绑定到 WPF xaml 中。在 xaml 中,我正在尝试使用 Listbox 元素。
绑定对象是这样的:
public SortedDictionary <TimeSpan, List<circles>> storage;
而且,班级圈子有:
int ID;
int Position_X;
int Position_Y;
string Circle_Color;
因此,存储结构将是这样的:
00:00:001 - 1, 100, 200, White
- 2, 200, 300, Black
- 3, 100, 150, Blue
00:00:020 - 1, 111, 222, Red
而且,解决方案文件的结构是这样的:
[Folder] - [File]
Models - Storage
ViewModels - MainViewModel.cs
- FrameSelectorViewModel.cs
- VideoControlViewModel.cs
Views - MainWindow.xaml
- FrameSelector.xaml
- VideoControl.xml
因此,每个 xaml 都将与 ViewModel 类绑定。
并且存储变量在 FrameSelectorViewModel 类中。而且,我想在 Hiericaly 上的 FrameSelector 视图上显示。但是,它没有工作。
简单地说,我在 FrameSelector.xaml 文件上尝试了这段代码。
<ComboBox Margin="0,5" ItemsSource="{Binding storage}">
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Key}" Margin="5,0,0,0"/>
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
在调试模式下,变量存储在 中,但未显示。
有什么答案吗?
感谢阅读!:0
解决方案
你只能绑定属性,目前你已经声明了变量
所有 ViewModel 都需要实现INotifyPropertyChanged接口以确保 UI 被触发以更新自身。
请注意,XAML 区分大小写,PropertyNames 必须与 Viewmodel 中的名称完全匹配。您将 TextBlock 绑定到“Key”,但没有这样的 Prop(也许是“ID”)?
使用
ObservableCollection<T>
而不是List<T>
,如果添加或删除元素,它们会通知 UI您可以使用
ObservableCollection<MyPairs>
with而不是 Dictionaryclass MyPairs //don't forget INotifyPropertyChanged if data changes on runtime { public TimeSpan Time {get;set;} public ObservableCollection<circles> circles {get;set;} }
推荐阅读
- android - 在 onMessageReceived 中显示默认通知
- java - 如何根据选项值获得左/右
- javascript - 如何在没有像 Multer 这样的依赖项的情况下通过管道上传文件?
- powershell - 局域网唤醒状态的 PowerShell 脚本
- css - 段落中的文本在省略时仅在弹性框中垂直居中
标签,它背后的原因是什么?
- php - 递归依赖注入图是坏的吗?
- javascript - 在 Javascript while 循环中使用“未定义”作为标记是否安全?
- javascript - $('#details').change() 不执行函数
- vue.js - 不能在 nuxt.js 项目中使用 vuetify 变量
- java - Spring Boot 组件扫描