如何在ListView中包含“所有项目”项?

时间:2012-07-05 11:10:15

标签: c# .net wpf xaml listview

我有一个窗口,显示在餐馆/商店的特定时间之间的销售额。当用户选择要查询的时间段时,它会显示该时间之间的销售数据。我还以编程方式创建用户列表,然后可以选择过滤查询。例如,我选择“迈克尔”用户,然后用户显示已归属于他的所有销售(在之前选择的时间范围内)。

创建ListView用户相当容易,但我试图在此列表中添加一个名为“所有用户”的项目。然后将其传递回查询,然后查询将通过某个属性(UserId = 999或其他任何内容来识别此用户。不重要)来再次使用所有用户的数据填充页面。

现在我必须退出页面并返回执行此操作。不是很优雅!

我打算在User中将ViewModel对象附加到从数据库EF生成的列表中,但它会创建一个IUsers列表,因此我无法实例化它的实际情况(也许我在这里非常愚蠢而且缺少一些基本的东西?)。

任何帮助实现这一目标的人都会非常感激。

2 个答案:

答案 0 :(得分:0)

您的UI通常会创建一个包装底层用户信息的视图模型。然后,您将拥有视图绑定的这些视图模型的集合。假设你有这个,那么将一个Sentinel实例添加到这个集合就很简单了。它可能看起来像这样:

// 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
    {
        ...
    }
}

在构建查询的代码中,您需要做的就是检查用户视图模型中的用户是否存在。如果没有,则无需在查询中附加任何用户选择。

答案 1 :(得分:0)

您可以尝试使用CompositeCollection设置ItemSource的{​​{1}} -

ListBox

但是你必须应用一些解决方法(比如使用BindingProxy)来使<ListBox> <ListBox.ItemsSource> <CompositeCollection> <CollectionContainer Collection="{Binding YourCollection}" /> <ListBoxItem Foreground="Magenta">Select All</ListBoxItem> </CompositeCollection> </ListBox.ItemsSource> </ListBox> 工作,因为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?

相关问题