以下是一个基于MVVM模式,使用TextBox和CheckBox对WPF DataGrid进行过滤的解决方法的示例代码:
首先,创建一个名为FilterViewModel的视图模型类,用于处理过滤逻辑和与视图的交互:
public class FilterViewModel : INotifyPropertyChanged
{
private ObservableCollection<ItemModel> items;
public ObservableCollection<ItemModel> Items
{
get { return items; }
set
{
items = value;
OnPropertyChanged(nameof(Items));
}
}
private string filterText;
public string FilterText
{
get { return filterText; }
set
{
filterText = value;
ApplyFilter();
OnPropertyChanged(nameof(FilterText));
}
}
private bool showOnlyChecked;
public bool ShowOnlyChecked
{
get { return showOnlyChecked; }
set
{
showOnlyChecked = value;
ApplyFilter();
OnPropertyChanged(nameof(ShowOnlyChecked));
}
}
public FilterViewModel()
{
// 初始化数据
Items = new ObservableCollection<ItemModel>
{
new ItemModel { Name = "Item 1", IsChecked = true },
new ItemModel { Name = "Item 2", IsChecked = false },
new ItemModel { Name = "Item 3", IsChecked = true },
// ...
};
}
private void ApplyFilter()
{
var filteredItems = Items.Where(item => item.Name.Contains(FilterText));
if (ShowOnlyChecked)
{
filteredItems = filteredItems.Where(item => item.IsChecked);
}
Items = new ObservableCollection<ItemModel>(filteredItems);
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
然后,在XAML中创建一个包含TextBox、CheckBox和DataGrid的视图,并绑定到FilterViewModel:
<Window x:Class="FilteringDataGridSample.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Filtering DataGrid Sample" Height="450" Width="800">
<Window.DataContext>
<local:FilterViewModel />
</Window.DataContext>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<TextBox Grid.Row="0" Text="{Binding FilterText, UpdateSourceTrigger=PropertyChanged}" />
<CheckBox Grid.Row="1" Content="Show only checked" IsChecked="{Binding ShowOnlyChecked}" />
<DataGrid Grid.Row="2" ItemsSource="{Binding Items}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="Name" Binding="{Binding Name}" />
<DataGridCheckBoxColumn Header="Is Checked" Binding="{Binding IsChecked}" />
</DataGrid.Columns>
</DataGrid>
</Grid>
</Window>
最后,将MainWindow设置为应用程序的起始点:
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
MainWindow mainWindow = new MainWindow();
mainWindow.Show();
}
}
这样,当用户在TextBox中输入过滤条件或勾选CheckBox时,DataGrid将根据FilterViewModel中的逻辑自动更新显示的行。