这是怎么回事。我有一个视图模型,我称之为webclient,并用项目填充可观察的集合。我需要在两个不同的页面中有两个不同的列表框,但是与viewmodel具有相同的ItemsSource。如何限制两个列表框之一中的项目数量而不影响其他项目?我试图使用.Take(限制)到正在创建项目的视图模型中,但影响两个列表框。如何限制observablecollection数据绑定列表框中的项目数量?
更新
视图模型
public class MainViewModel : INotifyPropertyChanged
{
public MainViewModel()
{
this.Items = new ObservableCollection<ItemViewModel>();
this.Mainlist = new CollectionViewSource();
}
public ObservableCollection<ItemViewModel> Items { get; private set; }
public CollectionViewSource Mainlist { get; set; }
void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
try
{
...............
//Ignore the dummy data in foreach loop. Just for showcase.
foreach (var item in Items)
{
//Items creation
this.Items.Add(new ItemViewModel()
{ LineOne = item });
}
this.Mainlist.Source = App.ViewModel.Items;
this.Mainlist.Filter += (s, a) =>
a.Accepted = App.ViewModel.Items.IndexOf((ItemViewModel)a.Item) < 10;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
.....................
}
在视图的侧
public MainPage()
{
InitializeComponent();
DataContext = App.ViewModel;
list.ItemsSource = App.ViewModel.Mainlist.View;
}
更新2
,我发现(不使用CollectionViewSource
)另一种选择是米AKE新public ObservableCollection<ItemViewModel> Mainlist { get; private set; }
,并使用一个更
foreach (var item in Items.Take(limit))
{
//Items creation
this.Mainlist.Add(new ItemViewModel()
{ LineOne = item });
}
为了填充的ObservableCollection并绑定列表框Mainlist。这是工作,但我认为这是不好的做法,因为这样我就重复了数据。有关于此的任何想法?
感谢@Eren但在我case“myList”是“App.ViewModel.Items”,它是可观察集合,所以我在IndeOf表达式中得到一个错误 – user1004994 2012-07-07 14:41:43
这应该没问题,因为ObservableCollection确实有一个IndexOf方法。 – 2012-07-07 16:48:50
错误是参数1:无法从'object'转换为'ItemViewModel' – user1004994 2012-07-07 17:06:41