听起来您正在使用 MVVM。你当然可以绑定到多个 ObservableCollections。问题真的是:你需要吗?您应该保留绑定到 ObserableCollections 的情况,以防您的 ViewModel 发生变化,并且您需要让您的视图随更改保持更新。
这是我为您准备的一个示例,该示例将一个 View 绑定到 ViewModel 中的两个 ObservableCollections 和一个 List。所以——是的——你当然可以绑定到你想要的任何东西。在这个例子中,两个 ObservableCollections 将交替更新。这有帮助吗?
如果对整个 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;
}));
};
}
}
}