如何使用多个ObservableCollection绑定视图

时间:2009-05-25 05:00:43

标签: .net observablecollection

我有一个带有多个ObservableCollection的ModelView。这是正确的方法,并且当视图调用视图模型时,所有ObservableCollection都需要重新填充数据,然后再次对所有CollectionViewSource进行绑定。

另外如何在viewmodel的构造函数之外调用CollectionViewSource.GetDefaultView,我得到一个错误,它只能在construtor中调用。

如果我为每个CollectionViewSource创建一个单独的ModelView,那么在使用ModelView绑定其中一个视图时,其余的控件也会被绑定,但这次使用空值并且不会调用所有的ModelView。

我真的很困惑该怎么做,请帮忙。

1 个答案:

答案 0 :(得分:0)

听起来你正在使用MVVM。你当然可以绑定到多个ObservableCollections。问题确实是:你需要吗?对于ViewModel正在更改的情况,您应该保留对ObserableCollections的绑定,并且需要使用更改来更新View。

这是一个例子,我为你提供了一个View,它绑定了两个ObservableCollections和一个ViewModel中的List。所以 - 是的 - 你当然可以绑定你想要的任何东西。在此示例中,两个ObservableCollections将交替更新。这有帮助吗?

我发布了此here的代码,如果它有助于整个vs项目。

查看:

<Window x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
    <StackPanel Orientation="Vertical">

        <TextBlock>Bind to List:</TextBlock>
        <ListView ItemsSource="{Binding Path=Users}" Height="20"/>

        <TextBlock>Bind to ObservableCollection1:</TextBlock>
        <ListView ItemsSource="{Binding Path=ObservableCollection1}" 
                 Height="100"/>

        <TextBlock>Bind to ObservableCollection2:</TextBlock>
        <ListView ItemsSource="{Binding Path=ObservableCollection2}" 
                 Height="100"/>

    </StackPanel>
</Window>

ViewModel(View绑定到此ViewModel)

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Timers;
using System.Windows;
using System.Windows.Threading;
namespace WpfApplication1
{
  public class Class1
  {
    public List<string> Users{get;set;}
    public ObservableCollection<string> ObservableCollection1 { get; set; }
    public ObservableCollection<string> ObservableCollection2 { get; set; }
    public Class1()
    {
      this.Users = new List<string>{ "bob", "mary" };

      this.ObservableCollection1 = new ObservableCollection<string>();
      this.ObservableCollection2 = new ObservableCollection<string>();
      int counter = 0;
      Timer t1 = new Timer();
      t1.Enabled = true;
      t1.Interval = 1000;
      t1.Elapsed += delegate
      {
        Application.Current.Dispatcher.Invoke(
        DispatcherPriority.Send, new Action(delegate
        {
          if(counter % 2 == 1)
            this.ObservableCollection1.Add(DateTime.Now.ToString());
          else
            this.ObservableCollection2.Add(DateTime.Now.ToString());
          ++counter;
        }));
      };
    }
  }
}