WPF列表视图查询

发布于:2024-08-22 ⋅ 阅读:(20) ⋅ 点赞:(0)

WPF列表视图查询

查询方法

ICollectionView _collectionView = CollectionViewSource.GetDefaultView(DataItems);
if (_collectionView == null)
{
    return ;
}
_collectionView.Filter = item => item is MetadataItemVO vo && vo.Name.Contains(SearchText, StringComparison.OrdinalIgnoreCase);

源码

View

<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

public partial class MetadataItemVO
{
    public string Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
}

ViewModel

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);
}

网站公告

今日签到

点亮在社区的每一天
去签到