2011-02-07 21 views
8

我有一個wpf-mvvm應用程序。我可以過濾來自xaml的集合嗎?

我有一個觀察的集合在我的視圖模型

public ObservableCollection<BatchImportResultMessageDto> ImportMessageList { get; set; } 

「BatchImportResultMessageDto」 包含兩個屬性..

結果type..and消息。結果類型可以是成功或失敗。

我需要在一個列表框中顯示成功,並在另一個列表框中失敗。

我可以做到這一點...在viewmodel中有2個可觀察的集合來保存成功/失敗。

public ObservableCollection<BatchImportResultMessageDto> ImportFailureMessageList { get; set; } // To hold the failure messages. 
public ObservableCollection<BatchImportResultMessageDto> ImportSuccessMessageList { get; set; } // To hold the sucess messages. 

但是有沒有其他更好的方法,以便我可以過濾它(沒有新的兩個集合)?

+0

是 - 帶有標記擴展,請參閱http://stackoverflow.com/questions/6461826/in-wpf-can-you-filter-a-collectionviewsource-without-code-behind – Slugart 2015-05-07 16:33:38

回答

11

您可以使用CollectionViewSource並使其成爲視圖模型的屬性,並直接從XAML綁定到該集合而不是您的ImportMessageList集合。將ImportMessageList集合設置爲CollectionViewSource的來源,然後配置謂詞以在CollectionViewSource上執行過濾。

喜歡的東西:

private ICollectionView messageListView; 
public ICollectionView MessageListView 
{ 
    get { return this.messageListView; } 
    private set 
    { 
     if (value == this.messageListView) 
     { 
     return; 
     } 

     this.messageListView = value; 
     this.NotifyOfPropertyChange(() => this.MessageListView); 
    } 
} 

... 


this.MessageListView = CollectionViewSource.GetDefaultView(this.ImportMessageList); 
this.MessageListView.Filter = new Predicate<object>(this.FilterMessageList); 

... 

public bool FilterMessageList(object item) 
{ 
    // inspect item as message here, and return true 
    // for that object instance to include it, false otherwise 
    return true; 
} 
+0

如何過濾CollectionViewSource? – Relativity 2011-02-07 16:56:56

+0

添加了過濾器示例 – devdigital 2011-02-07 17:06:47

10

您可以通過創建兩個CollectionViewSource對象,並設置每個過濾器做到這一點。

如何創建一個VM綁定在XAML中CVS(Source):

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> 
    <Window.Resources> 
     <CollectionViewSource Source="{Binding}" x:Key="customerView"> 
      <CollectionViewSource.GroupDescriptions> 
       <PropertyGroupDescription PropertyName="Country" /> 
      </CollectionViewSource.GroupDescriptions> 
     </CollectionViewSource> 
    </Window.Resources> 
    <ListBox ItemSource="{Binding Source={StaticResource customerView}}" /> 
</Window> 

如何篩選在代碼中的CVS後面(你可以使用反射來看看,如果你的模型的特性不想做一個參考吧Source):

<CollectionViewSource x:Key="MyCVS" 
           Source="{StaticResource CulturesProvider}" 
           Filter="MyCVS_Filter" /> 

與(代碼後面)

void MyCVS_Filter(object sender, FilterEventArgs e) 
{ 
    CultureInfo item = e.Item as CultureInfo; 
    if (item.IetfLanguageTag.StartsWith("en-")) 
    { 
     e.Accepted = true; 
    } 
    else 
    { 
     e.Accepted = false; 
    } 
} 
相關問題