如何在ListView中包含“所有项目”项目?
我有一个窗口,显示在某个餐厅/商店某段时间内的销售额。当用户选择要查询的时间段时,它会显示该时间段之间的销售数据。我也正在编程创建一个用户列表,然后可以选择过滤查询。例如,我选择“迈克尔”用户,然后用它显示已归因于他的所有销售额(在之前选定的时间范围内)。如何在ListView中包含“所有项目”项目?
创建用户的ListView
是相当简单的,但我试图在这个列表中添加一个可以读取“所有用户”的项目。然后这将被传递回查询,然后该查询将通过某个Property(UserId = 999或其他任何不重要)来识别该用户,以便再次使用所有用户的数据填充页面。
现在我必须退出该页面并返回执行此操作。不是很优雅!
我会追加在ViewModel
的列表是从数据库EF产生User
对象,但它创造的IUsers
列表,所以我不能实例化它的一个实际实例(也许我是令人难以置信的愚蠢在这里,我错过了一些基本的东西?)。
任何帮助实现这一目标将不胜感激。
您的用户界面通常会创建一个包装底层用户信息的视图模型。然后,您将拥有视图绑定到的这些视图模型的集合。假设你有这个,向这个集合添加一个标记实例是一件简单的事情。它可能是这个样子:
// this is your DAL class
public class User
{
}
// a view model to wrap the DAL class
public class UserViewModel
{
// a special instance of the view model to represent all users
public static readonly UserViewModel AllUsers = new UserViewModel(null);
private readonly User user;
public UserViewModel(User user)
{
...
}
// view binds to this to display user
public string Name
{
get { return this.user == null ? "<<All>>" : this.user.Name; }
}
}
public class MainViewModel()
{
private readonly ICollection<UserViewModel> users;
public MainViewModel()
{
this.users = ...;
this.users.Add(UserViewModel.AllUsers);
}
public ICollection<UserViewModel> Users
{
...
}
}
在你的代码,构造查询,所有你需要做的是检查在用户视图模型的用户是否存在。如果没有,则不需要将任何用户选择附加到查询上。
你可以尝试使用CompositeCollection设置你的ListBox
ItemSource
-
<ListBox>
<ListBox.ItemsSource>
<CompositeCollection>
<CollectionContainer Collection="{Binding YourCollection}" />
<ListBoxItem Foreground="Magenta">Select All</ListBoxItem>
</CompositeCollection>
</ListBox.ItemsSource>
</ListBox>
但是,你将不得不申请一些解决方法(如使用BindingProxy),使Binding
工作作为CollectionContainer不支持绑定,请参阅这些链接 -
http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/637b563f-8f2f-4af3-a7aa-5d96b719d5fd/
How do you bind a CollectionContainer to a collection in a view model?
我们需要一些代码,这是太多的文字。 – MBen 2012-07-05 11:15:00
来吧不要害羞。告诉我们你做了什么? – akhil 2012-07-05 11:18:16