2012-07-05 103 views
1

我有一個窗口,顯示在某個餐廳/商店某段時間內的銷售額。當用戶選擇要查詢的時間段時,它會顯示該時間段之間的銷售數據。我也正在編程創建一個用戶列表,然後可以選擇過濾查詢。例如,我選擇「邁克爾」用戶,然後用它顯示已歸因於他的所有銷售額(在之前選定的時間範圍內)。如何在ListView中包含「所有項目」項目?

創建用戶的ListView是相當簡單的,但我試圖在這個列表中添加一個可以讀取「所有用戶」的項目。然後這將被傳遞迴查詢,然後該查詢將通過某個Property(UserId = 999或其他任何不重要)來識別該用戶,以便再次使用所有用戶的數據填充頁面。

現在我必須退出該頁面並返回執行此操作。不是很優雅!

我會追加在ViewModel的列表是從數據庫EF產生User對象,但它創造的IUsers列表,所以我不能實例化它的一個實際實例(也許我是令人難以置信的愚蠢在這裏,我錯過了一些基本的東西?)。

任何幫助實現這一目標將不勝感激。

+1

我們需要一些代碼,這是太多的文字。 – MBen 2012-07-05 11:15:00

+0

來吧不要害羞。告訴我們你做了什麼? – akhil 2012-07-05 11:18:16

回答

0

您的用戶界面通常會創建一個包裝底層用戶信息的視圖模型。然後,您將擁有視圖綁定到的這些視圖模型的集合。假設你有這個,向這個集合添加一個標記實例是一件簡單的事情。它可能是這個樣子:

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

在你的代碼,構造查詢,所有你需要做的是檢查在用戶視圖模型的用戶是否存在。如果沒有,則不需要將任何用戶選擇附加到查詢上。

0

你可以嘗試使用CompositeCollection設置你的ListBoxItemSource -

<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?