WPF列表视图查询
查询方法
csharp
ICollectionView _collectionView = CollectionViewSource.GetDefaultView(DataItems);
if (_collectionView == null)
{
return ;
}
_collectionView.Filter = item => item is MetadataItemVO vo && vo.Name.Contains(SearchText, StringComparison.OrdinalIgnoreCase);
源码
View
xml
<DockPanel Margin="0,0,100,0">
<TextBlock VerticalAlignment="Center" Text="元数据项:" />
<Button
Margin="10,3,0,3"
Command="{Binding ResetSearchCommand}"
DockPanel.Dock="Right"
Content="重置" />
<Button
Margin="10,3,0,3"
Command="{Binding SearchCommand}"
DockPanel.Dock="Right"
Content="查询" />
<TextBox
Margin="0,3"
VerticalContentAlignment="Center"
Text="{Binding SearchText, Mode=TwoWay}" />
</DockPanel>
Model
csharp
public partial class MetadataItemVO
{
public string Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
ViewModel
csharp
private ObservableCollection<MetadataItemVO> _dataItems;
public ObservableCollection<MetadataItemVO> DataItems
{
get { return _dataItems; }
set { SetProperty(ref _dataItems, value); }
}
private string _searchText;
public string SearchText
{
get { return _searchText; }
set { SetProperty(ref _searchText, value); }
}
public ICommand ResetSearchCommand { get; set; }
public ICommand SearchCommand { get; set; }
private void InitCommands()
{
ResetSearchCommand = new RelayCommand(ResetSearch);
SearchCommand = new RelayCommand(Search);
}
private void ResetSearch()
{
ICollectionView _collectionView = CollectionViewSource.GetDefaultView(DataItems);
if (_collectionView == null)
{
return ;
}
_collectionView.Filter = item => true;
}
private void Search()
{
ICollectionView _collectionView = CollectionViewSource.GetDefaultView(DataItems);
if (_collectionView == null)
{
return ;
}
_collectionView.Filter = item => item is MetadataItemVO vo && vo.Name.Contains(SearchText, StringComparison.OrdinalIgnoreCase);
}