2014-10-30 56 views
0

在我的MainView我加了一個UserControlWPF MVVM一個的ObservableCollection多個列表視圖

<TabItem Header="Current Elements"> 
       <tabData:CurrentElementsControl DataContext="{Binding Path=EditorViewModel.SelectedConfigFile}"></tabData:CurrentElementsControl> 
      </TabItem> 

,並設置其DataContextSelectedConfigFile得到了存儲不同類型的元素的ObservableCollection<Elements>

UserControl基本上是一個ListView

<ListView Name="ServiceListView" 
              ItemsSource="{Binding Path=Elements}"            
              SelectedItem="{Binding Path=SelectedElement, Mode=TwoWay}" 
              Loaded="ServiceListView_Loaded"/> 

,我想顯示給定類型的ObservableCollection<Elements>的項目。 但我不想爲每個類型和列表視圖添加另一個ObservableCollectionSelectedConfigFile(VM)。所以我想我可以只設置一個過濾器爲我的用戶,利用其加載的事件是這樣的(在代碼隱藏):

 private void ServiceListView_Loaded(object sender, RoutedEventArgs e) 
    { 
     CollectionView view = (CollectionView)CollectionViewSource.GetDefaultView(this.ServiceListView.ItemsSource); 
     view.Filter = ServiceFilter; 
    } 

     private bool ServiceFilter(object item) 
    {   
     if (item is ServiceViewModel) { 
      return true; 
     } 
     else { 
      return false; 
     } 
    } 

但是,這將過濾ObservableCollection<Elements>藏漢,我需要在其他地方(未過濾)。有什麼建議麼?

預先感謝您!

回答

0

您顯然需要超過1個視圖。所以不要獲得無法以這種方式共享的默認視圖。嘗試建立這樣一個新的觀點:

private void ServiceListView_Loaded(object sender, RoutedEventArgs e) { 
    CollectionView view = new CollectionView(this.ServiceListView.ItemsSource); 
    view.Filter = ServiceFilter; 
    //use the created view here such as by assigning it to some ItemsSource 
    //... 
} 
+0

過濾現在不起作用。過濾器方法被調用並完成其工作,但所有元素都顯示在列表視圖中。 – user3596113 2014-10-30 07:10:38

+0

@ user3596113啊當然,我們創建了一個新的視圖,但是這個視圖目前還沒有被使用。你必須將這個視圖分配給一些ListView的'ItemsSource',我希望你能理解這個想法。 – 2014-10-30 07:22:02

+0

我想它不足以像這樣設置'ListView'' ItemsSource',是嗎? 'ServiceListView.ItemsSource = view;' – user3596113 2014-10-30 07:27:14

0

只要指定參考資料的DataTemplates與相應的數據類型是不夠的,例如

<ListView Name="ServiceListView" 
      ItemsSource="{Binding Path=Elements}"            
      SelectedItem="{Binding Path=SelectedElement, Mode=TwoWay}" 
      Loaded="ServiceListView_Loaded"/> 
    <ListView.Resources> 
     <!-- Do NOT set the x:Key --> 
     <DataTemplate DataType="{x:Type local:ElementType1}"> 
      <TextBlock Text="{Binding Name}" Foreground="Blue"/> 
     </DataTemplate> 
     <DataTemplate DataType="{x:Type local:ElementType2}"> 
      <TextBlock Text="{Binding Model}" Foreground="Red"/> 
     </DataTemplate> 
    </ListView.Resources> 
</ListView> 

如果您不想顯示特定類型的項目,請不要爲其定義項目模板。這樣原始集合保持不變,但只有某些元素會顯示給用戶。

相關問題