c# - 将集合绑定(bind)到列表控件

标签 c# xaml mvvm windows-8 winrt-xaml

您好,我正在学习 MVVM 和 Win8 应用程序开发,我在通过 XAML 将 ObservableCollection(位于 NoteViewModel.cs 中)绑定(bind)到我的 MainPage 列表框(或 ListView )时遇到了问题。

public ObservableCollection<Note> NotesList;

模型是一个简单的 Note.cs 类,它包含 NoteText、Priority 和 RemindDate。

我现在正在做的是在 MainPage.xaml.cs 的代码隐藏文件中设置 DataContext 到 ObservableCollection。

public MainPage()
{
    this.InitializeComponent();
    NoteViewModel nvm = new NoteViewModel();
    noteListView.DataContext = nvm.NotesList;
}

在 NoteViewModel 构造函数中,我简单地创建了 2 个新的 Notes,然后将其添加到 Collection 中。

我想做的是将 XAML 中的 DataContext 设置为 NoteViewModel,将 ItemsSource 设置为 NotesList。我想稍后为单个笔记实现 DetailsView。

有很多关于将集合绑定(bind)到列表框的教程, 但我还没有找到一个显示 MVVM 正确方法的方法。

有什么帮助吗?

最佳答案

您需要将您的 View (MainPage) 绑定(bind)到您的 ViewModel,而不是将列表的 DataContext 设置为集合

然后在 View 的 xaml 中,将列表的 ItemSource 绑定(bind)到 ViewModels NotesList 属性

例如

View 模型:

public NoteViewModel : INotifyPropertyChanged
{
  //Collection must be a property
  public ObservableCollection<Note> NotesList {get; private set;}

  public NoteViewModel()
  {
     //Initialize your collection in the constructor
     NotesList = new ObservableCollection<Note>()
  }

  //.
  //.
  //.

}

如果你愿意,你仍然可以在后面的代码中设置DataContext

public MainPage()
{
  this.InitializeComponent();
  NoteViewModel nvm = new NoteViewModel();
  this.DataContext = nvm;
}

或者,您可以通过 View 的 xaml 设置 DataContext。假设您的 ViewModel 在命名空间 MyProject 中:

添加对您的命名空间的引用

<UserControl x:class=MyProject.MainPage
  xmlns:local="clr-namespace:MyProject"
  .
  .
>

将 ViewModel 添加为资源

<UserControl.Resources>
  <local:NoteViewModel x:Key="NoteViewModel"/>
</UserControl.Resources>

将主容器的 DataContext 绑定(bind)到此资源

<Grid x:Name="LayoutRoot" DataContext="{StaticResource NoteViewModel}">

设置 DataContext 后,您需要通过绑定(bind)为 notesListView 控件设置 ItemSource

ItemSource={Binding NotesList}

关于c# - 将集合绑定(bind)到列表控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13282724/

相关文章:

c# - 从数据网格中获取复选框的值?

design-patterns - 在MVVM模型层次结构中共享值(value)

c# - WPF: Canvas 上的命令不起作用

c# - 将 String 转换为相应的 Forms.Keys 值?

c# - 隐藏元素与 DataTriggers

c# - 使用 Amazon SQS 的最佳实践 - 轮询队列

c# - 如何使用 Graphics.Draw 高效渲染图 block ?

wpf - 如何使用文本 block 在 xaml 网格上设置可滚动条

c# - 将文本 block 绑定(bind)到两个属性

c# - 在 WPF MVVM 中处理大量命令