如何绑定 SortedDicionary<Timespan, List<Class>> 存储与列表框,MVVM 模式?

How Binding SortedDicionary<Timespan, List<Class>> storage with Listbox, MVVM Pattern?

我是 C# 上的 MVVM 模式新手。 我正在尝试使用 MVVM 模式将变量绑定到 WPF xaml。 在 xaml 中,我尝试使用列表框元素。

绑定对象是这个:

public SortedDictionary <TimeSpan, List<circles>> storage;

并且,class 圈子有:

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 Class 绑定。

并且存储变量在 FrameSelectorViewModel Class 中。 而且,我想在 Hiericaly 的 FrameSelector View 上显示。 但是,没用。

简单地说,我在 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

  1. 您只能绑定属性,目前您已经声明了变量

  2. 所有 ViewModel 都需要实现 INotifyPropertyChanged 接口以确保 UI get 被触发以更新自身。

  3. 请注意,XAML 区分大小写,PropertyNames 必须与 Viewmodel 中的名称完全匹配。您将 TextBlock 绑定到 'Key' 但没有这样的 Prop(可能是 'ID')?

  4. 使用 ObservableCollection<T> 而不是 List<T>,如果添加或删除元素,它们会通知 UI

  5. 您可以使用 ObservableCollection<MyPairs>

    而不是字典
    class MyPairs //don't forget INotifyPropertyChanged if data changes on runtime
    {
      public TimeSpan Time {get;set;}
      public ObservableCollection<circles> circles {get;set;}
    }