我在试验 WPF 时遇到了一些我没想到的过滤行为。
我用 ListView 和 DataGrid 创建了一个简单的 Window 控件,它显示有关美国总统的信息,例如姓名、政党和数字顺序。
该应用程序实例化一个带有多个总统的 ObservableCollection。在 Main 中,从 ObservableCollection 创建一个视图,并应用过滤和排序。ListView 绑定到这个视图,DataGrid 绑定到原来的 ObservableCollection。
我希望 ListView 显示过滤后的结果,而 DataGrid 显示列表中的所有项目。但是,DataGrid 也会显示过滤后的结果。有人对此有解释吗?
public partial class MainWindow : Window
{
ICollectionView presidentView;
ObservableCollection<President> presidents = new ObservableCollection<President>
{
new President{Name = "Barack Obama", Party="Democratic", Order=44},
new President {Name = "George W Bush", Party="Republican", Order=43},
new President{Name = "Bill Clinton", Party="Democratic", Order=42},
new President {Name="George Bush", Party="Republican", Order=41},
new President{Name="Ronald Reagan", Party="Republican", Order=40},
new President{Name="Jimmy Carter", Party="Democratic", Order=39},
new President{Name="Gerald Ford", Party="Republican", Order=38},
new President{Name="Richard Nixon", Party="Republican", Order=37},
new President{Name="Lyndon Johnson", Party="Democratic", Order=36}
};
public MainWindow()
{
InitializeComponent();
presidentView = CollectionViewSource.GetDefaultView(presidents);
presidentView.SortDescriptions.Add(new SortDescription("Order", ListSortDirection.Ascending));
Predicate<object> isRepublican = (x) =>
{
President p = x as President;
return p.Party == "Republican";
};
presidentView.Filter = isRepublican;
list.ItemsSource = presidentView;
grid.ItemsSource = presidents;
}
}
public class President
{
public int Order { set; get; }
public string Name { set; get; }
public string Party { set; get; }
}
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication2"
Title="MainWindow" Height="350" Width="727.416">
<Grid>
<ListView HorizontalAlignment="Left" Height="260" Margin="10,10,0,0" Name="list" VerticalAlignment="Top" Width="197">
<ListView.ItemTemplate>
<ItemContainerTemplate>
<TextBlock Text="{Binding Path=Name}">
</TextBlock>
</ItemContainerTemplate>
</ListView.ItemTemplate>
</ListView>
<DataGrid Name="grid" HorizontalAlignment="Left" Margin="224,13,0,0" VerticalAlignment="Top" Height="257" Width="487"/>
</Grid>
</Window>