I have an observable collection of type A.
Class A contains an enum - IsWhite.
My observable collection is called ACollection.
I also have 2 datagrids, one that will have an itemssource bound to ACollection where the A items have IsWhite set to false, the other datagrid which is bound to the same collection but with IsWhite set to true.
How can I achieve this?
The collection is declared as follows;
ObservableCollection<A> ACollection = new ObservableCollection<A>;
and the class
public class A
{
IsWhite isWhiteEnum { get; set; } = IsWhite.False;
}
I want one datagrid itemssource to bind to ACollection populating the items where IsWhite is False and the other datagrid itemssource to bind to ACollection popualting items where IsWhite is True.
Here's a precis of the relevent parts of the article here:
https://social.technet.microsoft.com/wiki/contents/articles/26673.wpf-collectionview-tips.aspx
You don't want to filter the default view of a collection because that way your filter would apply to both datagrids.
This bit of code gets two independent views:
PeopleView = (CollectionView)new CollectionViewSource { Source = People }.View;
LevelsPeopleView = (CollectionView)new CollectionViewSource { Source = People }.View;
People is an observablecollection of person.
Both those views are collectionviews, eg.
public CollectionView LevelsPeopleView { get; set; }
The views are bound in TwoCollectionViews.xaml eg
<DataGrid ....
ItemsSource="{Binding PeopleView}"
And the article illustrates various filters such as the msdn approach:
private void ShowOnlyBargainsFilter(object sender, FilterEventArgs e)
{
AuctionItem product = e.Item as AuctionItem;
if (product != null)
{
// Filter out products with price 25 or above
if (product.CurrentPrice < 25)
{
e.Accepted = true;
}
else
{
e.Accepted = false;
}
}
}
Or much more sophisticated approaches.
You set a filter:
LevelsPeopleView.Filter = FirstOfLevel_Filter;
If the view has already grabbed the data out that collectionview then nothing will happen. You need to also do
LevelsPeopleView.Refresh();
This sort of filtering is quite inefficient and linq is better at large datasets. Still better is small datasets. Unless your users really really like scrolling.
Related
I have an app that retrieves data from a database and displays it in data grid on the main window. The maximum number of items being displayed is ~5000.
I don't mind a time delay in display the results, but i'd like to display a loading animation whilst this is happening. However, even when using a background worker to update the collection view source the UI freezes before displaying the rows.
Is it possible to add all these rows without freezing the UI? Apply filters to the collection view source also seems to freeze the UI which i'd like to avoid also if possible.
Thanks in advance!
UPDATE 06.01.2023
Updated as per the suggestions from BionicCode and Andy and now everything is running very smoothly - thank you for the help!
XAML for the data grid:
<DataGrid Grid.Column="1" Name="documentDisplay" ItemsSource="{Binding Source={StaticResource cvsDocuments}, UpdateSourceTrigger=PropertyChanged, IsAsync=True}" AutoGenerateColumns="False"
Style="{StaticResource DataGridDefault}" ScrollViewer.CanContentScroll="True"
HorizontalAlignment="Stretch" HorizontalContentAlignment="Stretch" ColumnWidth="*">
XAML for collection view source:
<Window.Resources>
<local:Documents x:Key="documents" />
<CollectionViewSource x:Key="cvsDocuments" Source="{StaticResource documents}"
Filter="DocumentFilter">
Code within function being called after retrieving data from database:
Documents _documents = (Documents)this.Resources["documents"];
BindingOperations.EnableCollectionSynchronization(_documents, _itemsLock);
if (!populateDocumentWorker.IsBusy)
{
progressBar.Visibility = Visibility.Visible;
populateDocumentWorker.RunWorkerAsync(jobId);
}
Code within worker:
Documents _documents = (Documents)this.Resources["documents"];
lock (_itemsLock)
{
_documents.Clear();
_documents.AddRange(documentResult.documents);
}
Observable collection class:
public class Documents : ObservableCollection<Document>, INotifyPropertyChanged
{
private bool _surpressNotification = false;
protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{
if (!_surpressNotification)
{
base.OnCollectionChanged(e);
}
}
public void AddRange(IEnumerable<Document> list)
{
if(list == null)
{
throw new ArgumentNullException("list");
_surpressNotification = true;
}
foreach(Document[] batch in list.Chunk(25))
{
foreach (Document item in batch)
{
Add(item);
}
_surpressNotification = false;
}
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}
}
Base class for observable collection:
public class Document : INotifyPropertyChanged, IEditableObject
{
public int Id { get; set; }
public string Number { get; set; }
public string Title { get; set; }
public string Revision { get; set; }
public string Discipline { get; set; }
public string Type { get; set; }
public string Status { get; set; }
public DateTime Date { get; set; }
public string IssueDescription { get; set; }
public string Path { get; set; }
public string Extension { get; set; }
// Implement INotifyPropertyChanged interface.
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(String info)
{
if(PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
private void NotifyPropertyChanged(string propertyName)
{
}
// Implement IEditableObject interface.
public void BeginEdit()
{
}
public void CancelEdit()
{
}
public void EndEdit()
{
}
}
Filter Function:
private void DocumentFilter(object sender, FilterEventArgs e)
{
//Create list of all selected disciplines
List<string> selectedDisciplines = new List<string>();
foreach(var item in disciplineFilters.SelectedItems)
{
selectedDisciplines.Add(item.ToString());
}
//Create list of all select document types
List<string> selectedDocumentTypes = new List<string>();
foreach(var item in docTypeFilters.SelectedItems)
{
selectedDocumentTypes.Add(item.ToString());
}
// Create list of all selected file tpyes
List<string> selectedFileTypes = new List<string>();
foreach(var item in fileTypeFilters.SelectedItems)
{
selectedFileTypes.Add(item.ToString());
}
//Cast event item as document object
Document doc = e.Item as Document;
//Apply filter to select discplines and document types
if( doc != null)
{
if (selectedDisciplines.Contains(doc.Discipline) && selectedDocumentTypes.Contains(doc.Type) && selectedFileTypes.Contains(doc.Extension))
{
e.Accepted = true;
} else
{
e.Accepted = false;
}
}
}
There are a couple of problems with your design here.
The way the filter of a collectionview works is it iterates through the collection one by one and returns true/false.
EDIT:
Experimentation seems to confirm this statement is true. AFAIK virtualisation is purely in creation of UI from the collection. Collectionviewsource > Collectionview > Itemssource. Creation of UI rows is virtualised by the virtualising stackpanel but the whole collection will be read into itemssource.
Your filter is complicated and will take a while per item.
It's running 5000 times.
You should not use that approach to filter.
A rethink and fairly substantial refactor is advisable.
Do all your processing and filtering in a Task you run as a background thread.
Forget all that synchronisation context stuff.
Once you've done your processing, return a List of your finalised data back to the UI thread
async Task<List<Document>> GetMyDocumentsAsync
{
// processing filtering and really expensive stuff.
return myListOfDocuments;
}
If that doesn't get edited or sorted then set a List property your itemssource is bound to.
If it does either then new up an observablecollection
YourDocuments = new Observablecollection<Document>(yourReturnedList);
passing your list as a constructor paremeter and set a observablecollection property your itemssource is bound to.
Hence you do ALL your expensive processing on a background thread.
That is returned to the UI thread as a collection.
You set itemssource to that via binding.
The custom observablecollection is a bad idea. You should just use List or Observablecollection where t is a viewmodel. Any viewmodel should implement inotifypropertychanged. Always.
Two caveats.
Minimise the number of rows you present to the UI.
If it's more than a couple of hundred then consider paging and maybe an intermediate cache.
Remove this out your binding
, UpdateSourceTrigger=PropertyChanged
And never use it again until you know what it does.
Some generic datagrid advice:
Avoid column virtualisation.
Minimise the number of columns you bind.
If you can, have fixed column widths.
Consider the simpler listview rather than datagrid.
The problem is your Filter callback. Currently you iterate over three lists inside the event handler (in order to create the filter predicate collections for lookup).
Since the event handler is invoked per item in the filtered collection, this introduces excessive work load for each filtered item.
For example, if each of the three iterations involves 50 items and the filtered collection contains 5,000 items, you execute a total of 5035000 = 750,000 iterations (150 for each event handler invocation).
I recommend to maintain the collections of selected items outside the Filter event handler, so that it doesn't have to be created for each individual item (event handler invocation). The three collections are only updated when a related SelectedItems property has changed.
To further speed up the lookup in the Filter event handler I also recommend to replace the List<T> with a HashSet<T>.
While List.Contains is an O(n) operation, HashSet.Containsis O(1), which can make a huge difference.
You need to track the SelectedItems that are the source for those collections separately to update them.
The following example should speed up your filtering significantly.
/* Define fast O(1) lookup collections */
private HashSet<string> SelectedDisciplines { get; set; }
private HashSet<string> SelectedDocumentTypes { get; set; }
private HashSet<string> SelectedFileTypes { get; set; }
// Could be invoked from a SelectionChanged event handler
// (what ever the source 'disciplineFilters.SelectedItems' is)
private void OnDisciplineSelectedItemsChanged()
=> this.SelectedDisciplines = new HashSet<string>(this.disciplineFilters.SelectedItems.Select(item => item.ToString()));
// Could be invoked from a SelectionChanged event handler
// (what ever the source 'docTypeFilters.SelectedItems' is)
private void OnDocTypeSelectedItemsChanged()
=> this.SelectedDocumentTypes = new HashSet<string>(this.docTypeFilters.SelectedItems.Select(item => item.ToString()));
// Could be invoked from a SelectionChanged event handler
// (what ever the source 'fileTypeFilters.SelectedItems' is)
private void OnFileTypeSelectedItemsChanged()
=> this.SelectedFileTypes = new HashSet<string>(this.fileTypeFilters.SelectedItems.Select(item => item.ToString()));
private void FilterDocuments(object sender, FilterEventArgs e)
{
// Cast event item as document object
if (e.Item is not Document doc) //if (!(e.Item is Document doc))
{
return;
}
// Apply filter to select discplines and document types
e.Accepted = this.SelectedDisciplines.Contains(doc.Discipline)
&& this.SelectedDocumentTypes.Contains(doc.Type)
&& this.SelectedFileTypes.Contains(doc.Extension);
}
Remarks
You should fix your Documents.AddRange method.
It should use the NotifyCollectionChangedAction.Add. NotifyCollectionChangedAction.Replace will trigger the binding target to completely update itself, which is what you want to avoid.
Use the appropriate NotifyCollectionChangedEventArgs constructor overload to send the complete range of added items with the event:
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, list as IList ?? list.ToList()));
Further considerations
Since you said you read the data from a database, you should consider to let the database filter the data for you. Given the correct query, the database will provide far better performance as it is highly optimized for filtering (search queries).
Using the filter feature of the ICollectionView will always block the UI until the collection is filtered. This is because the procedure is not asynchronous. This means you can't display a progress bar as it won't update in real time. Consider to prefilter the items when fetching them from the database. It doesn't make sense to load 5k items when the user can only view 10-50 of them.
If you want to display a progress bar, you better filter the collection directly. This requires a dedicated binding source collection. Since you have already implemented a custom ObservableCollection that exposes a AddRange method, you are good to go (don't forget to fix the CollectionChanged event data).
To add grouping you have to take into consideration that
a) grouping disables row virtualization
b) grouping actually takes place in the UI. The control creates a GroupItem for each group.
To fix a) you need to explicitly enable virtualization while grouping by setting the attached VirtualizingPanel.IsVirtualizingWhenGrouping to true:
<DataGrid VirtualizingPanel.IsVirtualizingWhenGrouping="True" />
To fix b) you could use LINQ grouping, which you could execute on a background thread if necessary:
IEnumerable<IGrouping<string, Document>> groupedDocuments = FilteredItemsSource.DataGridItems.GroupBy(document => document.Author);
dataGrid.ItemsSource = groupedDocuments;
The problem is that DataGrid doesn't know how to display IGrouping. You have to get creative here. Probably extending DataGrid to add this feature would be the best.
If this is not an option, then the only solution I think that is reasonable is to implement data virtualization.
I generally believe that it doesn't make sense to show 5k items at once while the user can only view a fraction.
Just imagine you have 5k items in two groups each of 2.5k items. When the user opens the first, he needs to scroll down 2.5k items before he can see the second group. The UX couldn't get any worse at this point.
If this was my problem to solve, I would reduce the number of items to load. Additionally I would ask myself if the data structure is the correct form to display the data. For example you could create top-down filtering: like first let user select an author, then a created date, etc. Use this filter information to query the database. This should significantly reduce the number of items to display/handle.
Alternatively create an index or use an indexing service like Elastic Search. Such service come with a very advanced query syntax that allow to search/filter the indexed documents more comfortable.
What you are currently doing is not efficient at all and provides a really bad UX.
The following example extends the basic example from above.
You need to bind your DataGrid to the FilteredItemsSource property while you populate the UnfilteredDocuments property with the data from the database.
The example also shows how to replace the CollectionViewSource in XAML with a ICollectionView that is more convenient to handle from C# (code-behind).
it also shows how to gracefully toggle a ProgressBar using the .NET BooleanToVisibilityConverter.
MainWindow.xaml
<Window>
<Window.Resources>
<!-- Use the existing .NET value converter -->
<BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" />
</Window.Resources>
<StackPanel>
<ProgressBar IsIndeterminate="True"
Height="4"
Visibility="{Binding ElementName=Window, Path=IsFilterInProgress, Converter={StaticResource BooleanToVisibilityConverter}}" />
<DataGrid ItemsSource="{Binding FilteredItemsSource, Mode=OneTine}"
VirtualizingPanel.IsVirtualizingWhenGrouping="True"
AutoGenerateColumns="False">
</DataGrid>
</StackPanel>
</Window>
*MainWindow.xaml.cs
// The binding source for the ProgressBar.
// Can be bound to Visibility or used as predicate for a Trigger
// This property must be implemented as dependency property!
public bool IsFilterInProgress { get; private set; }
// Binding source for the ItemsControl
public Documents FilteredItemsSource { get; } = new Documents();
// Structure for the database data
private List<Document> UnfilteredDocuments { get; } = new List<Document>();
/* Define fast O(1) lookup collections */
private HashSet<string> SelectedDisciplines { get; set; }
private HashSet<string> SelectedDocumentTypes { get; set; }
private HashSet<string> SelectedFileTypes { get; set; }
private object SyncLock { get; } = new object();
// Constructor
public MainWindow()
{
InitializeComponent();
// Enable CollectionChanged propagation to the UI thread
// when updating a INotifyCollectionChanged collection from a background thread
BindingOperations.EnableCollectionSynchronization(this.FilteredItemsSource, this.SyncLock);
}
// Could be invoked from a SelectionChanged event handler
// (what ever the source 'disciplineFilters.SelectedItems' is)
private async void OnDisciplineSelectedItemsChanged(object sender, EventArgs e)
{
this.SelectedDisciplines = new HashSet<string>(this.disciplineFilters.SelectedItems.Select(item => item.ToString()));
await ApplyDocumentFilterAsync();
}
// Could be invoked from a SelectionChanged event handler
// (what ever the source 'docTypeFilters.SelectedItems' is)
private async void OnDocTypeSelectedItemsChanged(object sender, EventArgs e)
{
this.SelectedDocumentTypes = new HashSet<string>(this.docTypeFilters.SelectedItems.Select(item => item.ToString()));
await ApplyDocumentFilterAsync();
}
// Could be invoked from a SelectionChanged event handler
// (what ever the source 'fileTypeFilters.SelectedItems' is)
private async void OnFileTypeSelectedItemsChanged(object sender, EventArgs e)
{
this.SelectedFileTypes = new HashSet<string>(this.fileTypeFilters.SelectedItems.Select(item => item.ToString()));
await ApplyDocumentFilterAsync();
}
private async Task ApplyDocumentFilterAsync()
{
// Show the ProgressBar
this.IsFilterInProgress = true;
// Allow displaying of a progress bar (prevent the UI from freezing)
await Task.Run(FilterAndSortDocuments);
// Because grouping is actually happening in the UI (by creating GroupItems)
// we can't group on a background thread.
GroupDocuments();
// Hide the ProgressBar
this.IsFilterInProgress = false;
}
// Improve performance by filtering and sorting in one step.
// Use FilterDocuments() if filtering alone (no sorting) is required.
private void FilterAndSortDocuments()
{
IEnumerable<Document> filteredDocuments = GetFilteredDocuments();
// For example sort descending by the property Document.Id
IOrderedEnumerable<Document> filteredAndSortedDocuments = filteredDocuments
.OrderByDescending(document => document.Id);
this.FilteredItemsSource.AddRange(filteredAndSortedDocuments);
}
private void FilterDocuments()
{
this.FilteredItemsSource.Clear();
IEnumerable<Document> filteredDocuments = GetFilteredDocuments();
this.FilteredItemsSource.AddRange(filteredDocuments);
}
private void GroupDocuments()
{
ICollectionView filteredItemsSourceCollectionView = CollectionViewSource.GetDefaultView(this.FilteredItemsSource);
// Allow multiple GroupDescription.Add() and Clear()
// without raising change notifications every time.
// A single change notification is raised after leaving the using scope.
using (var deferredRefreshContext = filteredItemsSourceCollectionView.DeferResfresh())
{
GroupDescriptions groupDescriptions = filteredItemsSourceCollectionView.GroupDescriptions;
groupDescriptions.Clear();
groupDescriptions.Add(new PropertyGroupDescription(nameof(Document.Author)));
}
}
private IEnumerable<Document> GetFilteredDocuments()
{
IEnumerable<Document> filteredDocuments = this.UnfilteredDocuments.Where(IsDocumentAccepted);
return filteredDocuments;
}
private bool IsDocumentAccepted(Document document)
=> this.SelectedDisciplines.Contains(doc.Discipline)
&& this.SelectedDocumentTypes.Contains(doc.Type)
&& this.SelectedFileTypes.Contains(doc.Extension);
I have a small caliburn micro MVVM project with a DataGrid. The columns will consist of x amount of 'setup's and the rows will consist of 'CustomRow'. I would like to use a ObservableCollection where CustomRow has a function property and a collection of setup property. For each setup in this collection a column should exist with the value of setup.
class CustomRow
{
public string Function { get; set; }
public ObservableCollection<Setup> Setups { get; set; }
}
// example class
class Setup
{
public string Name { get; set; }
public object Content { get; set; }
}
So I need to be able to add columns and rows dynamically depending on the itemssource (all the Setups collections will have the same size).
My problem is that I don't know how to translate the Setups property into multiple columns.
I have spend quit some time on what should be a mundane problem in my opinion. But I am missing something.
Any help is much appreciated.
Bind or set the ItemsSource to the ObservableCollection<CustomRow> and then get the Setups property of the first CustomRow in the source collection in the view, e.g.:
private void Window_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
var vm = DataContext as YourViewModel;
dataGrid.Columns.Clear();
if (vm.Rows != null && vm.Rows.Count > 0)
{
var setups = vm.Rows[0].Setups;
foreach (var setup in setups)
{
dataGrid.Columns.Add(new DataGridTextColumn { Header = setup.Name, Binding = new Binding("Content ") });
}
}
dataGrid.ItemsSource = vm.Rows;
}
There is no way to bind the Columns property of the DataGrid directly to a source property so you need to create the columns yourself one way or another.
You should do this in the view, in the control or in an attached behaviour that is attached to either of them. A view model should not create any columns.
I have a method that queries a database using entity framework and places the results in an ICollectionView. The ICollectionView acts as the ItemsSource for a DataGrid. Everything works fine on the first query, but upon querying a second time, the data is not properly sorted, despite the application of the correct SortDescriptions.
Here is my code for trying querying and grouping/sorting the data:
CollectionViewSource cvsRS;
private ObservableCollection<productorder> rs;
public ObservableCollection<productorder> RS
{
get { return rs; }
set
{
if (rs != value)
{
rs = value;
OnPropertyChanged("RS");
}
}
}
private ICollectionView rsView;
public ICollectionView RSView
{
get { return rsView; }
set
{
if (rsView != value)
{
rsView = value;
OnPropertyChanged("RSView");
}
}
}
public void QueryDatabase()
{
RS = new ObservableCollection<productorder>(DatabaseEntities.productorders.Where(o => o.month.id == CurrentMonth.id));
if (RS != null)
{
cvsRS.Source = RS;
RSView = cvsRS.View;
RSView.GroupDescriptions.Clear();
RSView.GroupDescriptions.Add(new PropertyGroupDescription("producttype.productcategory.name"));
RSView.GroupDescriptions.Add(new PropertyGroupDescription("producttype.name"));
RSView.SortDescriptions.Clear();
RSView.SortDescriptions.Add(new SortDescription("producttype.productcategory.sortorder", ListSortDirection.Ascending));
RSView.SortDescriptions.Add(new SortDescription("client.name", ListSortDirection.Ascending));
RSView.Refresh();
CurrentRecord = null;
SelectedRecords = null;
}
}
The grouping works fine, but the groups aren't in the correct order based on the sorting. I've tried a number of possible "fixes" with no success (e.g. adding sort/group descriptions directly to the CollectionViewSource, sorting before grouping, removing some of the sorting/grouping, removing the SortDescriptions per CollectionViewSource does not re-sort on property change).
Does anyone know how to maintain the sort order regardless of how many queries are performed? I'm open to alternative methods of querying displaying the data in the DataGrid if that may work.
Try binding your CollectionViewSource.Source property to your ObservableCollection<T> property. Set up the binding in the viewmodel constructor. Then, just leave it alone. Update the ObservableCollection<T>, replace it, etc. As long as it's an ObservableCollection<T> and its public property raises PropertyChanged whenever you replace it, the whole thing will work.
public MyViewModel()
{
BindCollectionViewSource();
}
protected void BindCollectionViewSource()
{
cvsRS = new CollectionViewSource();
var binding = new Binding
{
Source = this,
Path = new PropertyPath("RS")
};
BindingOperations.SetBinding(cvsRS, CollectionViewSource.SourceProperty, binding);
}
// Since we're not going to be messing with cvsRS or cvsRS.View after the
// constructor finishes, RSView can just be a plain getter. The value it returns
// will never change.
public ICollectionView RSView
{
get { return cvsRS.View; }
}
You can't just assign a binding to Source; there's more to it than that. The Source="{Binding RSView}" stuff you see in XAML may look like an assignment, but some details are being hidden for convenience. The Binding actively does stuff. It needs to know who the target object is.
I did see one funny thing: I gave my test code one PropertyGroupDescription and one SortDescription. When I added items to the collection, it sorted them within the groups. Then when I called RSView.Refresh(), it resorted them without reference to the groups. Not sure I understood what it was doing there.
Is there any way to automatically update a filter on an ICollectionView without having to call Refresh() when a relevant change has been made?
I have the following:
[Notify]
public ICollectionView Workers { get; set; }
The [Notify] attribute in this property just implements INotifyPropertyChanged but it doesn't seem to be doing anything in this situation.
Workers = new CollectionViewSource { Source = DataManager.Data.Workers }.View;
Workers.Filter = w =>
{
Worker worker = w as Worker;
if (w == null)
return false;
return worker.Employer == this;
};
In XAML:
<TextBlock x:Name="WorkersTextBlock"
DataContext="{Binding PlayerGuild}"
FontFamily="Pericles"
Text="{Binding Workers.Count,
StringFormat=Workers : {0},
FallbackValue=Workers : 99}" />
Update: It looks like using ICollectionView is going to be necessary for me, so I'd like to revisit this topic. I'm adding a bounty to this question, the recipient of which will be any person who can provide some insight on how to implement a 'hands-off' ICollectionView that doesn't need to be manually refreshed. At this point I'm open to any ideas.
AFAIK there is no inbuilt support in ICollectionView to refresh collection on any property change in underlying source collection.
But you can subclass ListCollectionView to give it your own implementation to refresh collection on any property changed. Sample -
public class MyCollectionView : ListCollectionView
{
public MyCollectionView(IList sourceCollection) : base(sourceCollection)
{
foreach (var item in sourceCollection)
{
if (item is INotifyPropertyChanged)
{
((INotifyPropertyChanged)item).PropertyChanged +=
(s, e) => Refresh();
}
}
}
}
You can use this in your project like this -
Workers = new MyCollectionView(DataManager.Data.Workers);
This can be reused across your project without having to worry to refresh collection on every PropertyChanged. MyCollectionView will do that automatically for you.
OR
If you are using .Net4.5 you can go with ICollectionViewLiveShaping implementation as described here.
I have posted the implementation part for your problem here - Implementing ICollectionViewLiveShaping.
Working code from that post -
public ICollectionViewLiveShaping WorkersEmployed { get; set; }
ICollectionView workersCV = new CollectionViewSource
{ Source = GameContainer.Game.Workers }.View;
ApplyFilter(workersCV);
WorkersEmployed = workersCV as ICollectionViewLiveShaping;
if (WorkersEmployed.CanChangeLiveFiltering)
{
WorkersEmployed.LiveFilteringProperties.Add("EmployerID");
WorkersEmployed.IsLiveFiltering = true;
}
For .Net 4.5:
There is a new interface which can help to achieve this feature, called : ICollectionViewLiveShaping.
From MSDN link:
When live sorting, grouping, or filtering is enabled, a CollectionView
will rearrange the position of data in the CollectionView when the
data is modified. For example, suppose that an application uses a
DataGrid to list stocks in a stock market and the stocks are sorted by
stock value. If live sorting is enabled on the stocks' CollectionView,
a stock's position in the DataGrid moves when the value of the stock
becomes greater or less than another stock's value.
More Info on above interface:
http://www.jonathanantoine.com/2011/10/05/wpf-4-5-%E2%80%93-part-10-live-shaping/
For .Net 4 and lower:
There is also another post on SO QA which might help you:
CollectionViewSource Filter not refreshed when Source is changed
About Data Virtualizatoin in WPF, the WPF: Data Virtualization is a good article.
With using this, Data Virtualization was executed as good in my code but there is the one problem, which is that I cannot bind a property in ViewModel with SelectedItem of ItemsControl in View. If one item of data satisfies some condition while data loads, the one item will be set as a property in ViewModel and then it will be bound with SelectedItem of ItemsControl in View, but will not.
My code about this is the following. About the types of IItemsProvider andVirtualizingCollection, please refer to the WPF: Data Virtualization.
So far, I have tried:
I'm sure that if Data Virtualization were not used, the Selected Item Binding would be cool.
The IndexOf(T item) method in VirtualizingCollection returns always -1. As thinking this would be the problem, I implemented that the IndexOf(T item) returns a actual index, but it was not concerned with this problem.
The code of implementing IItemsProvider
public class WordViewModelProvider : IItemsProvider<WordViewModel>
{
private string _searchText = "some text";
public WordViewModel SelectedItem
{
get;
private set;
}
#region IItemsProvider<WordViewModel> Members
public int FetchCount()
{
lock (_words)
{
int count = (from word in _words
where word.Name.Contains(_searchText)
select word).Count();
return count;
}
}
public IList<WordViewModel> FetchRange(int startIndex, int count)
{
lock (_words)
{
//Please, regard _word as IEnumerable<Word>
IQueryable<Word> query = (from word in _words
where word.Name.Contains(_searchText)
select word);
List<WordViewModel> result = query.ToList().ConvertAll(w =>
{
var wordViewModel = new WordViewModel(w, _searchText);
if (w.Name.Equals(_searchText, StringComparison.InvariantCultureIgnoreCase))
{
SelectedItem = wordViewModel;
}
return wordViewModel;
});
return result;
}
}
#endregion
}
The code of using VirtualizingCollection in ViewModel
public void ViewList()
{
var wordViewModelProvider = new WordViewModelProvider();
var virtualizingCollection = new VirtualizingCollection<WordViewModel>(wordViewModelProvider);
//IList<WordViewModel> type to bind with View's ItemsSource.
WordViewModels = virtualizingCollection;
//WordViewModel type to bind with View's SelectedItem
SelectedItem = wordViewModelProvider.SelectedItem;
}
I would like to post good references about Virtualization to deal with large data set in WPF.
UI Virtualization vs Data Virtualization.
For Virtualization approaches:
Paul McClean
Vincent Van Den Berghe
bea.stollnitz: He/She describes the solution that combines some of the best features of the two former and covers my issue.