2010-11-11 85 views
2

我無法得到明確的答案。 我有一個Static類(DataHolder),它包含一個具有複雜類型(CustomerName和CustomerID屬性)的靜態列表。 我想將它綁定到WPF中的列表框,但添加另一個項目,將有單詞「全部」爲未來的拖放功能。 有人嗎?如何將WPF中的列表框綁定到通用列表?

回答

2

創建一個可以綁定到數據綁定的ViewModel類! ViewModel可以引用靜態類並將這些項目複製到它自己的集合中,並將所有項目添加到它。

像這樣

public class YourViewModel 
{ 
     public virtual ObservableCollection<YourComplexType> YourCollection 
     { 
      get 
      { 
       var list = new ObservableCollection<YourComplexType>(YourStaticClass.YourList); 
       var allEntity = new YourComplexType(); 

       allEntity.Name = "all"; 
       allEntity.Id = 0; 

       list.Insert(0, allEntity); 

       return list; 
      } 

     } 
} 

注意,有時候,你需要的空項。由於WPF無法將數據綁定爲空值,因此需要使用相同的方法來處理它。空的商業實體是它的最佳實踐。只是谷歌它。

+0

很好,這真的解決了我的問題。 – user437631 2010-11-12 07:14:18

0

如果您使用綁定而不是所提供的數據作爲源必須保存所有項目,即。你不能數據綁定,然後添加另一個項目到列表中。

您應該將「全部」項目添加到DataHolder集合中,並在您的代碼中分別處理「全部」項目。

1

「所有」項必須是您綁定ListBox的列表的一部分。 Natuarally你不能將該項目添加到DataHolder列表中,因爲它包含Customer類型的項目(或類似項目)。您當然可以添加一個「魔術」客戶,總是充當「全部」項目,但這是明顯的原因,嚴重的設計氣味(畢竟是客戶名單)。

你可以做的是不直接綁定到DataHolder列表,而是引入一個包裝器。這個包裝將是你的ViewModel。您將再次綁定您的ListBox CustomerListItemViewModel的列表,表示客戶或「全部」項目。

CustomerViewModel 
{ 
    string Id { get; private set; } 
    string Name { get; set; } 
    public static readonly CustomerViewModel All { get; private set; } 

    static CustomerViewModel() 
    { 
     // set up the one and only "All" item 
     All = new CustomerViewModel(); 
     All.Name = ResourceStrings.All; 
    } 


    private CustomerViewModel() 
    { 
    } 

    public CustomerViewModel(Customer actualCustomer) 
    { 
     this.Name = actualCustomer.Name; 
     this.Id = actualCustomer.Id; 
    } 
} 

someOtherViewModel.Customers = new ObservableCollection<CustomerViewModel>(); 
// add all the wrapping CustomerViewModel instances to the collection 
someOtherViewModel.Customers.Add(CustomerViewModel.All); 

,然後在將&刪除代碼某處視圖模型:

if(tragetCustomerViewModelItem = CustomerViewModel.All) 
{ 
    // something was dropped to the "All" item 
} 

我可能剛纔您介紹的MVVM在WPF的好處。從長遠來看,它爲您節省了很多麻煩。