CollectionViewSource does not re-sort on property change - c#

I'm binding ItemsControl to CollectionViewSource. Here is code:
this.Trucks = new ObservableCollection<Truck>();
foreach (var truck in DataRepository.Trucks.Where(t => t.ReadyDate.Date.Equals(this.Date)))
{
this.Trucks.Add(truck);
}
this.TrucksSource = new CollectionViewSource { Source = this.Trucks };
this.TrucksSource.SortDescriptions.Add(new SortDescription("ReadyAddress.Region.RegionNumber", ListSortDirection.Ascending));
this.TrucksSource.SortDescriptions.Add(new SortDescription("TruckId", ListSortDirection.Ascending));
When I initially bind - sorting works. When I add item to ObservableCollection - it is inserted in proper spot, thats good. But when I change property which I sort by - this item is not being "shifted" in a list.
ReadyAddress.Region.RegionNumber properly raises INotifyPropertyChanged and I see it in bound fields, but order does not change. Do I expect something that shouldn't happen or there is better way to handle this?

Late answer, but with 4.5 the ListCollectionView (the default implementation for a ListBox and CollectionViewSource.View) new properties were added to make this possible.
You can use the IsListSorting and ListSortingProperties to enable automatic resorting. And no, it does not rebuild the view
list.SortDescriptions.Add(new SortDescription("MyProperty", ListSortDirection.Ascending));
list.IsLiveSorting = true;
list.LiveSortingProperties.Add("MyProperty");
This should resort when the property MyProperty changes.

Have you tried refreshing your collectionviewsource?
this.TruckSource.View.Refresh();

All answers I found mentioned View.Refresh() but that's not very good solution for big lists. What I ended up doing was to Remove() and Add() this item. Then it was properly repositioned without reloading whole list.
Word of caution! It works for what I do, but in your case removing object and re-adding may cause side effect depending how your code written. In my case it's a list with UI effect where new items show up with transition so refreshing will show transition on whole list where remove/add nicely shows how item get's repositioned.

Related

Why is my listView not updating after changing itemsource?

I have a listview which receives information from a HashSet, but when I delete one item of the HashSet, my listview is not updated.
And my listview doesn't have a method of refresh, don't know why. Here is my code:
private void deleteActivityFromAlumn(String activityName, String nif)
{
Alumn alumnDelete = Alumn.findAlumnByNIF(nif);
Activity activityDelete = Activity.getActivityByName(activityName);
Debug.WriteLine(alumnDelete.Name + activityDelete.Name);
alumnDelete.activities.Remove(activityDelete);
activityDelete.Alumns.Remove(alumnDelete);
listActivities.ItemsSource = alumnDelete.activities;
}
And the item is deleted in a right way because if I go search for the object again, it is removed from the listView, but I believe that its supposed to be updated when you refresh the ItemsSource.
To make sure that control with bound items changes when those items change you have to
Either make that collection implement INotifyCollectionChanged. The simplest way to do it is to use ObservableCollection<T> instead of HashSet<T>
Though you will lose the uniqueness property that HashSet<T> gives you.
Or to somehow force a refresh of that control when you change the collection. Though one has to take into account that it is not the best solution, as it will more often than not cause a full redrawing of the control with obvious performance and/or display issues.
Either by calling the Refresh method (WPF, WinForms)
Or by re-binding the collection
listActivities.ItemsSource = null;
listActivities.ItemsSource = alumnDelete.activities

Load ObservableCollection from Xml save file to Datagrid (C#, Wpf)

Okay so I hope it's okay if I don't post my code since it contains private parts.
I will describe it as good as I can. So I did an observablecollection without onpropetychange and a databind to the grid. Everything works well if I'm adding something to the collection, the datagrid updates. But if I get the observablecollection from the xml save file, it doesn't update.
So far I checked if the observablecollection loads everything (it does) and tried to update the datagrid manual (nothing). I'm glad if someone could give me advice without seeing the code. :)
If you are changing the whole collection, the UI can not recognize the change since you are not using the INotifyPropertyChanged. You have two options:
Implement the INotifyPropertyChanged and raise the event after setting a new collection as source.
Clear the old collection, and fill in the new items to the old collection.
My best guess is that you should set the DataGrid's ItemsSource property again after loading the ObservableCollection.
Use this:
datagrid.ItemsSource = null;
datagrid.ItemsSource = yourObservableCollection;

Removing an item from a WPF binding listbox

I have a WPF application with a ListBox (called listMyItems) which is successfully bound to a class of MyItems that I created. I have a List of MyItems called currentMyItems which is then assigned as ItemSource to the ListBox. It all works fine, if I add an item to the currentMyItems it pops up on the list, etc.
The problem occurs when I try to remove the selected item in the ListBox. This is the code that I use:
currentMyItems.Remove((MyItem)listMyItems.SelectedItem);
The item disappears from the ListBox but the next time I update it, it pops back up as it was never deleted. Any tips?
I think you may be confused about how data binding works. When you bind a property, you are telling WPF to go look somewhere else for the value of that property.
When you bind the ListBox.ItemsSource property to currentMyItems, you are telling WPF to go look at the currentMyItems list to find its list of items. If currentMyItems is an ObservableCollection instead of a List<T>, then the UI will automatically receive a notification to update the bound value when you add or remove an item from the collection.
Based on what you say in the question, it sounds like you you have two collections, one of which is bound, and the other which is used to recreate the first collection anytime a change occurs. All that is not needed.
Just create one ObservableCollection<MyItem>, bind it to the ListBox.ItemsSource property, and then add or remove items from that single collection. It should work as you would expect.
<ListBox x:Name="listMyItems" ItemsSource="{Binding MyItems}" />
and
MyItems.Add((MyItem)listMyItems.SelectedItem)
MyItems.Remove((MyItem)listMyItems.SelectedItem)
If you're interested, I also have some beginner articles on my blog for WPF users who are struggling to understand the DataContext. You may want to check out Understanding the change in mindset when switching from WinForms to WPF and What is this “DataContext” you speak of?
If you bound it correctly to an ObservableCollection and currentMyItems is that collection. Than it means that you must have reloaded currentMyItems in meantime.
Also consider binding the SelectedItem property of your ListView - your view model doesn't have to know about the view at all.
Your source collection must be modufy (inherit from IList or ICollection). If your source collection does not support this method of your interface Remove, you can't remove item from source.
So, when you want to remove item you must cast ItemsSource to IList or ICollection:
var source = listbox.ItemsSource as IList ?? listbox.ItemsSource as ICollection;
and then check:
if (source == null) return;
then:
listbox.SelectedItems.ForEach(source.Remove);
listbox.Items.Refresh();
Make the currentMyItems<MyItem> an ObservableColection<MyItem>. This way it will raise a property change whenever modified and the UI gets updated accordingly.
By using ObservableCollection you will automatically get updates on the UI.
You should use an ObservableCollection instead of List.
A good thing is to always use ObservableCollection instead of List when something to do with UI

Binding to an ICollectionView converted to a dictionary

As I am quite new to WPF and MVVM, this might be something quite obvious and trivial, so bear with me here.
Anyway, I have a view model with these properties:
class ViewModel : INotifyPropertyChanged {
ICollectionView Items; // a list of Items object, wraps _items field, each Item has a Date property
string Filter; // a filter key, wraps _filter field and calls ApplyFilter() as it is changed
void ApplyFilter(); // based on the filter key, _items.Filter gets set to some predicate
}
The properties raise the PropertyChanged event when set and all that common MVVM stuff.
In the view i have a simple ItemsControl which binds to the Items property, and some fancy data template to display each Item.
A request has been made to show the items grouped by day so that you see a date header for each day and a list of Items whose Date property corresponds to the date in the header.
Since this is strictly a display issue, I decided to leave the view model as it is, but use a converter to convert the ICollectionView Items into a Dictionary where the key is the date, and the collection is a subset of Items with that date.
The ItemsControl now has a StackPanel with a TextBlock to show the date header (the dictionary key) and another ItemsControl which is basically a copy of the old one, which just listed the items (the dictionary value).
The view renders nicely, but the filter no longer works. As the control is bound to Items, and the ICollectionView implements INotifyCollectionChanged, I was expecting the filter to work as it is changing the Items list, and that the converter would be re-run to rebuild the dictionary. Well, it is not. Changing the filter does call the ApplyFilter(), and the _items.Filter gets set to the required predicate, but the view never changes. I have also tried calling the PropertyChanged for Items from the ApplyFilter, but that does not work either.
Obviously, my contrived scenario of how this should work is wrong, and to be honest I am out of ideas, apart from creating new objects which will hold the date and list of items as properties and then using a list of those in the VM. But, as I said, in my mind, this is strictly a view issue, so the model just needs to provide a list of items, and it is the view's responsibility to decide how to render them.
Any help is greatly appreciated and thanks in advance.
EDIT:
Now I'm thinking that if I'm changing the _filter.Filter, then the PropertyChanged event for the Items is actually never raised, as it is in fact not changed (the internals have changed, but Items themselves are still the same ICollectionView).
Hence, the converter is never again triggered.
If this is the case, how can I trigger the converter? Raising the PropertyChanged for Items after doing ApplyFilter() also did nothing.
Perhaps using ListView instead of simple ItemsControl+converter is better idea? ListView has many good functions. Such as virtualizing, grouping, etc.
All you have to do, is modify your ICollectionView grouping property and apply templates(GroupStyle)
As for your problem, your current behaviour makes sense to me. If you want to converter re-run, you're supposed to create new method RefreshBinding() and do something like this;
var referenceCopy = Items;
Items = null;//make sure INotifyPropertyCHanged is fired.
Items = referenceCopy; //converter should be called again.
you will call it after you need your converter to be re-run. But to be completely honest, just use ICollectionView+Grouping property and ListView. Or you can implement ListView functionality yourself. Using converter does not seem good solution.

How do I keep the selection in ListBox when reloading ItemsSource

I am experimenting with WPF and MVVM in our system. However iam having a problem with keeping things selected in lists using only MVVM ( without doing extra CollectionViews ).
What i currently have is the list
ObservableCollection<ReservationCustomerList> Customers;
And then a property storing the selected Customer
ReservationCustomerList SelectedCustomer;
In my opinion now, when the list reloads (actually from another thread async), the selection should be able to be kept, however this does not happen.
Does someone have a nice clean way of achieving this ?
The way we did it was that we did not replace the collection. We added/removed the entries and updated existing entries if required. This maintains the selection.
You can use LINQ methods like Except to identify items that are new or removed.
In case the reloaded list still contains the last selected item and you want that item to be selected, then you can raise the PropertyChange event for the property SelectedCustomer after your collection gets reloaded.
Please make your sure your viewmodel class implements INotifyPropertyChanged interface.
you can use the ICollectionView to select the entity you want.
ICollectionview view = (ICollectionView)CollectionViewSource.GetDefaultView(this.Customers);
view.MoveCurrentTo(SelectedCustomer);
in your Xaml the itemsControl must have IsSynchronizedWithCurrentItem=true
or if the ItemsControl has a SelectedItem property you can simply bind it to your SelectedCustomer Property.
When you "reload" your collection you basically replace all values in it with new values. Even those that look and feel identical are in fact new items. So how do you want to reference the same item in the list when it is gone? You could certainly use a hack where you determine the item that was selected by its properties and reselect it (i.e. do a LINQ search through the list and return the ID of the matching item, then reselect it). But that would certainly not be using best practices.
You should really only update your collection, that is remove invalid entried and add new entries. If you have a view connected to your collection all the sorting and selecting and whatnot will be done automagically behind the scenes again.
Edit:
var tmp = this.listBox1.SelectedValue;
this._customers.Clear();
this._customers.Add(item1); this._customers.Add(item2);
this._customers.Add(item3); this._customers.Add(item4);
this.listBox1.SelectedValue = tmp;
in the method that does the reset/clear works for me. I.e. that is the code I put into the event handling method called when pressing the refresh button in my sample app. That way you dont even need to keep references to the customer objects as long as you make sure that whatever your ID is is consistent. Other things I have tried, like overwriting the collections ´ClearItems()´ method and overwriting ´Equals()´ and ´GetHashCode()´ didn't work - as I expected.

Categories

Resources