[英]How to Bind Listbox in WPF to a generic list?
我無法為此獲得明確的答案。 我有一個靜態類(DataHolder),它包含一個復雜類型的靜態列表(CustomerName和CustomerID屬性)。 我想將它綁定到WPF中的ListBox,但添加另一個將具有單詞“All”的項目,以用於將來的拖放功能。 任何人?
創建一個可以數據綁定到的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無法數據綁定為空值,因此您需要使用相同的方法來處理它。 空業務實體是最佳實踐。 只是谷歌吧。
“All”項必須是綁定ListBox的列表的一部分。 通常,您無法將該項添加到DataHolder列表,因為它包含Customer(或類似)類型的項。 你當然可以添加一個“神奇”的客戶,它總是充當“全部”項目,但這顯然是一個嚴重的設計氣味案例(畢竟它是一個客戶列表)。
你可以做的是不直接綁定DataHolder列表,而是引入一個包裝器。 這個包裝器將是你的ViewModel。 您將再次將ListBox綁定到CustomerListItemViewModel列表,該列表表示Customer或“All”項。
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);
然后在ViewModel中的某個拖放代碼中:
if(tragetCustomerViewModelItem = CustomerViewModel.All)
{
// something was dropped to the "All" item
}
我可能剛剛向您介紹了WPF中MVVM的優點。 從長遠來看,它可以為您節省很多麻煩。
如果您使用綁定而不是提供的數據,因為源必須包含所有項目,即。 你不能數據綁定,然后添加另一個項目到列表中。
您應該將“All”項添加到DataHolder集合中,並在代碼中單獨處理“All”項。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.