在我的wpf窗口中,我有兩個列表框。一個用於可用項目,另一個用於所選項目。當沒有過濾時,可用項目通常會保存3000+項目。用戶將看到一個組合框來過濾項目類型和一個文本框來過濾項目名稱。目前我使用Linq來過濾這些項目,但它非常緩慢地刷新列表。我想知道是否有更好的方法。快速高效地過濾綁定到ViewModel中的集合的列表框
感興趣的一些注意事項:我創建了一個附加行爲,允許將所選項目(注意's')屬性綁定到視圖模型,並且此行爲需要一個集合類型才能工作。 我有文本過濾器設置爲更新時更改屬性,並在屬性設置器中調用過濾器方法。
查看:
<DatePicker Grid.Row="0" Grid.Column="1" Height="26" VerticalAlignment="Center" SelectedDate="{Binding FromDate}" />
<DatePicker Grid.Row="0" Grid.Column="3" Height="26" VerticalAlignment="Center" SelectedDate="{Binding ToDate}" />
<ComboBox Grid.Row="1" Grid.Column="1" Height="22" VerticalAlignment="Center" ItemsSource="{Binding Classes}" SelectedItem="{Binding SelectedClass}" />
<TextBox Grid.Row="4" Grid.Column="1" Height="22" VerticalAlignment="Center" Text="{Binding CiNameFilterText, UpdateSourceTrigger=PropertyChanged}" Margin="55,0,0,178" />
<ListBox Grid.Row="4" Grid.Column="1" Height="172" ItemsSource="{Binding AvailableCis}" DisplayMemberPath="CiName" SelectionMode="Extended" Ocean_WPF:ListBoxBehavior.SelectedItems="{Binding AvailableCisSelected}" Margin="0,28,0,0" />
<ListBox Grid.Row="4" Grid.Column="3" Height="200" ItemsSource="{Binding SelectedCis}" DisplayMemberPath="CiName" SelectionMode="Extended" Ocean_WPF:ListBoxBehavior.SelectedItems="{Binding SelectedCisSelected}" />
視圖模型:
Protected Sub FilterCiList()
Try
If (_caCiData IsNot Nothing) Then
If ((_selectedClass IsNot Nothing AndAlso Not _selectedClass.Equals(String.Empty)) AndAlso (_ciNameFilterText IsNot Nothing AndAlso Not _ciNameFilterText.Equals(String.Empty))) Then
Me.AvailableCis = New ObservableCollection(Of CA.SoftwareRow)(_caCiData.Where(Function(ci) ci.Class.ToUpper.Equals(_selectedClass.ToUpper) AndAlso ci.CiName.ToUpper.Contains(_ciNameFilterText.ToUpper)).OrderBy(Function(a) a.CiName))
ElseIf ((_selectedClass IsNot Nothing AndAlso Not _selectedClass.Equals(String.Empty)) AndAlso (_ciNameFilterText Is Nothing OrElse _ciNameFilterText.Equals(String.Empty))) Then
Me.AvailableCis = New ObservableCollection(Of CA.SoftwareRow)(_caCiData.Where(Function(ci) ci.Class.ToUpper.Equals(_selectedClass.ToUpper)).OrderBy(Function(a) a.CiName))
ElseIf ((_selectedClass Is Nothing OrElse _selectedClass.Equals(String.Empty)) AndAlso (_ciNameFilterText IsNot Nothing AndAlso Not _ciNameFilterText.Equals(String.Empty))) Then
Me.AvailableCis = New ObservableCollection(Of CA.SoftwareRow)(_caCiData.Where(Function(ci) ci.CiName.ToUpper.Contains(_ciNameFilterText.ToUpper)).OrderBy(Function(a) a.CiName))
Else
Me.AvailableCis = New ObservableCollection(Of CA.SoftwareRow)(_caCiData.OrderBy(Function(a) a.CiName))
End If
If (Me.SelectedCis IsNot Nothing) Then
For Each Ci In Me.SelectedCis
Me.AvailableCis.Remove(Ci)
Next
End If
End If
Catch ex As Exception
_viewModelUIService.ExceptionDialog(ex)
End Try
End Sub
_caCiData是完整的未篩選列表。如果我篩選列表,我只需要顯示與篩選器匹配的項目,因此我只是使用Linq查詢將這些項目添加到AvailableCis屬性中。
必須有一個更好的方式來做到這一點作爲過濾速度慢(大約需要5秒鐘它能夠刷新視圖列表之前)
編輯:我的一個朋友提出了一個數據視圖,將是比每次過濾整個集合都更好嗎?