2010-11-11 87 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的好处。从长远来看,它为您节省了很多麻烦。