i read some articles about having DataGrid
filtered automatically, usingCollectionViewSource
, so then i used it, but i found it will stop working after a few clicks. i would be nice if somebody could let me know what goes wrong.
work in .net 4.5.
following is a small demo that could reproduce the problem:
xaml:
<Window x:Class="WpfApplication9.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"Title="MainWindow"Height="350"Width="525"><Grid><DataGrid x:Name="dg"Margin="0,32,0,0"/><ComboBox x:Name="combo"VerticalAlignment="Top"Margin="0,5,80,0"SelectionChanged="combo_SelectionChanged"/><ButtonContent="Button"Margin="0,7,0,0"VerticalAlignment="Top"HorizontalAlignment="Right"Width="75"Click="Button_Click"/></Grid></Window>
c#:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfApplication9{/// <summary>/// Interaction logic for MainWindow.xaml/// </summary>publicpartialclassMainWindow:Window{publicMainWindow(){InitializeComponent();}void cvs_Filter(object sender,FilterEventArgs e){if((e.ItemasWrap)==null|| combo.SelectedItem==null)return;if((e.ItemasWrap).Int==(int)combo.SelectedItem)
e.Accepted=true;else
e.Accepted=false;}privatevoid combo_SelectionChanged(object sender,SelectionChangedEventArgs e){(dg.ItemsSourceasICollectionView).Refresh();}privatevoidButton_Click(object sender,RoutedEventArgs e){var oc =newObservableCollection<Wrap>(from i innew[]{1,2,3,4,1,5,3,6,7,8,9,2,3,6,7,8,4,3,7,9,8,4,4,3,2,2}selectnewWrap{Int= i });
combo.ItemsSource=Enumerable.Range(1,9);var cvs =newCollectionViewSource();
cvs.Source= oc;
cvs.Filter+= cvs_Filter;
dg.ItemsSource= cvs.View;
combo.SelectedIndex=0;}}classWrap{publicintInt{ get;set;}}}
result:
at the beginning:
it works fine. but after a few clicks:
couldn't get into event handler.