> 使用 Listbox、MVVM 模式存储?,c#,mvvm,binding"/>

首页 > 解决方案 > 如何绑定 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

标签: c#mvvmbinding

解决方案


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

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

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

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

  5. 您可以使用ObservableCollection<MyPairs>with而不是 Dictionary

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

推荐阅读