我正在尝试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>
答案 0 :(得分:4)
CollectionViewSource.GetDefaultView(object)
返回给定源的相同ICollectionView
实例 - 在显示源集合时将用于任何ItemsControl
(DataGrid
){{1} 1}})。
您可以通过创建一个新的presidents
实例来解决这个问题,该实例将由您希望独立于其他控件的每个控件使用(通常,每个不同的过滤器使用不同的控件)。
更新您的ICollectionView
以实例化如下:
presidentView