我的应用程序中有一个窗口,其中包含以下资源:
<Window.Resources>
<ResourceDictionary>
<Data:IssueRecords x:Key="DataSource"/>
<CollectionViewSource x:Key="DataCollection" Source="{StaticResource DataSource}"
Filter="CollectionViewSource_Filter">
</CollectionViewSource>
</ResourceDictionary>
</Window.Resources>
有一个标准的事件处理程序 - 一个名为CollectionViewSource_Filter和DataGrid的方法,用于应用过滤器。我的窗口加载后,一切都很完美,包括过滤器。
为了应用过滤器,我调用了ReloadGrid方法......
private void ReloadGrid(object sender, RoutedEventArgs e)
{
CollectionViewSource.GetDefaultView(GridData.ItemsSource).Refresh();
}
但是,当用户执行任何操作(对我的数据库进行更改(删除,修改或创建新)时),我需要重新加载这些数据源,所以我打电话给...
private void ReloadDataSources()
{
var dataSource = this.FindResource("DataSource") as IStockRecords;
dataSource.ReloadData();
var dataCollection = this.FindResource("DataCollection") as CollectionViewSource;
dataCollection = new CollectionViewSource() { Source = dataSource };
dataCollection.Filter += new FilterEventHandler(CollectionViewSource_Filter);
Binding binding = new Binding() { Source = dataCollection };
BindingOperations.SetBinding(GridData, DataGrid.ItemsSourceProperty, binding);
}
我认为,我做了所有事情,从数据库中读取实际数据并在窗口中重新加载数据源所需的一切。但是当我使用任何过滤器时,在调用ReloadDataSources()之后,过滤器事件不再被使用。我调试了一个源代码,而且当我设置FilterEventHandler时,Refresh方法不会调用CollectionViewSource_Filter ......
我错过了什么吗? 谢谢,JiKra
答案 0 :(得分:2)
修改数据源后,您需要重置默认视图。
CollectionViewSource.GetDefaultView(GridData.ItemsSource).Refresh();
试试这个......
private void ReloadDataSources()
{
var dataSource = this.FindResource("DataSource") as IStockRecords;
dataSource.ReloadData();
var dataCollection = this.FindResource("DataCollection") as CollectionViewSource;
// Remove the current event handler
dataCollection.Filter -= new FilterEventHandler(CollectionViewSource_Filter);
// Set your new data source
dataCollection = new CollectionViewSource() { Source = dataSource };
// Read your handler
dataCollection.Filter += new FilterEventHandler(CollectionViewSource_Filter);
// Now reset your filter
dataCollection .GetDefaultView(GridData.ItemsSource).Refresh();
Binding binding = new Binding() { Source = dataCollection };
BindingOperations.SetBinding(GridData, DataGrid.ItemsSourceProperty, binding);
}
答案 1 :(得分:1)
好的,我重新创建CollectionViewSource对象时似乎有问题。所以,最终版本是......
private void ReloadDataSources()
{
var dataSource = this.FindResource("DataSource") as IStockRecords;
dataSource.ReloadData();
var dataCollection = this.FindResource("DataCollection") as CollectionViewSource;
//here I just had to refresh collection's view, not to create a new one
dataCollection.View.Refresh();
Binding binding = new Binding() { Source = dataCollection };
BindingOperations.SetBinding(GridData, DataGrid.ItemsSourceProperty, binding);
}
谢谢你的努力...... JiKra