I need to handle the PropertyChanged event of an item in an ObservableCollection within the owner of the ObservableCollection. There has to be a more elegant way than:
ObservableCollection(MyViewModel) myViewModels = new ObservableCollection<MyViewModel>();
LoadMyViewModels(myViewModels); // populates the collection
foreach (MyViewModel myViewModel in myViewModels)
{
myViewModel.PropertyChanged += PropertyChangedEventHandler(MyViewModelPropertyChanged);
}
I'd like to pass the MyViewModelPropertyChanged event handler into LoadMyViewModels so I don't have to traverse the collection twice (once on load and once on event assignment).
MyViewModelPropertyChanged sets properties on the containing view that are reflected on the UI (the collection is bound to a TreeView and I need to enable/disable fields in the UI based on whether the item has been checked).
I've looked at most if not all the cited postings, but I'm a bit lost.
The above code does what I need it to do, but I know there's a better way. Please cite the appropriate reference or code sample.
Thanks.
A BindingList may give you what you need...
BindingList relays item change notifications when its items implement INotifyPropertyChanged.
Related
Background:
I was trying to roll my own observable collection, by implementing IEnumerable, INotifyPropertyChanged and INotifyCollectionChanged. It works fine, but when I databind the CollectionChanged event is always null. The databound property does however updated, since I am sending a Items[] property changed event.
So this got me wondering what the point of INotifyCollectionChanged is in terms of databinding, since in my class it never gets triggered, but the databinding still works (it updates all the bindings to the collection).
I then decided to do some more digging, and decompiled ObservableCollection. When I databind to an ObservableCollection the CollectionChanged event isn't null like in my implementation.
So really I am wondering why ObservableCollection gets 'special' treatment, and what role INotifyCollectionChange plays in databinding (if any)
INotifyCollectionChanged can be implemented by collections so that when elements are added or removed from the collection, interested parties can be notified of those events. This is useful, for example, when you want a ListView or GridView or some other display control that displays the contents of collections to update its display when the contents of the collection have changed (through adding or removing elements). More generally, any object could data bind to the event to be notified when items are added/removed from the collection to do whatever the data bound component needs to do—it doesn't just have to be a GUI control. Any other operations on the collection, however, will result in no notifications being made to data bound controls/objects. In order for that to occur, you would also need to implement INotifyPropertyChanged on the collection, creating the other PropertyChanged events you also want to publish to notify data bound objects, and raise the event when the operation in question occurs.
Additionally, if you want each item within the collection to update its presentation in the UI when something about the item itself has changed, then the type representing the item should implement INotifyPropertyChanged.
It seems to me that you need to implement your own CollectionChanged event. The built-in System.Array and/or System.Collections.ArrayList classes do not have any events associated with them. So if you're using one of these classes as your backing store, then on each addition/removal of an item, you would need to be sure to raise the CollectionChanged event for your custom collection implementation.
However, I need to ask, why roll your own observable collection when Microsoft already provides the ObservableCollection<T> object, which you could possibly subclass and receive the functionality you're looking for for free?
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.
I have a listbox with items bound to an ObservableCollection.
Now, from within the viewModel, I need to cause an update to the UI.
I dont have a refernce to the listbox from my view model.
If I remove or add an item from my ObservableCollection, the ui gets updated.
Based on some other logic I need to update the UI...but the ObservableCollection is the same.
How can I update the UI WITHOUT either adding or removing items from my ObservableCollection?
Thanks
If you need to change your UI because you've edited the items in your collection, then you should arrange for those items to implement the INotifyPropertyChanged interface. If the objects within your collection have a PropertyChanged event, the UI will be listening for that event from individual items. (If possible, you could also change the items in your collection to be DependencyObjects with DependencyProperties, which accomplishes the same goal.)
If you really need to trigger a UI update when nothing at all about your collection has changed, the way to do it is to manually raise the CollectionChanged event. This can't be done with the ObservableCollection<> as is, but you could derive a new collection from that class, and call the protected OnCollectionChanged method from within some new, public method.
I've had a similar issue where I wanted to change the background on an item, but obviously neither the item nor the collection changed.
It was achieved by calling:
CollectionViewSource.GetDefaultView(your_collection_name).Refresh();
This refreshed the view from the view model without altering the collections
This is a good case for an extension method. It hides away the implementation in case it changes in future versions, can be modified in one place, and the calling code looks simpler and less confusing.
public static void Refresh<T>(this ObservableCollection<T> value)
{
CollectionViewSource.GetDefaultView(value).Refresh();
}
Usage:
myCollection.Refresh();
I am binding a BindingList two way to a listbox. The Binding list contains a number of images which apparently only update the listbox if items are added or removed from the binding list. How can I make it so that the bindinglist also raises the listchanged event when an item is modified?
EDIT: I find the problem I am having is that a property of an object is not being changed, rather the base object.
BindingList<ImageSource>();
This wont work however if I did this:
BindingList<Image>();
And then set the binding path to Image.Source, it would update correctly and this is because a property of the Image has changed but in the case of the first example, only a direct item in the list has changed. So how may I get the same behaviour as the second example?
FINAL EDIT : It seems that using ObservableCollection instead of BindingList fixes this issue. I was under the impression that they were identical in notifying of changes in the collection. Full answer below
The list does raise that event but only if the underlying items provides the proper notifications via INotifyPropertyChanged.
The BindingList differs from ObservableCollection in that BindingList does not notify that its direct items are changed (except when items are added or removed from the collection). ObservableCollection however implements INotifyCollectionChanged and INotifyPropertyChanged interfaces. This means that any change to direct items of an ObservableCollection are reported to the UI.
If you are using bindings to direct items and need to update items and not properties of those items, it seems that you have to use ObservableCollection. Another solution would be to derive from BindingList and implement INotifyCollectionChanged.
I am not an expert but this is what i have gathered during the last hour, if anyone has anything to add or correct please let me know.
I have a situation where I need to know when an item is going to be added/removed/modified in the collection.
I tried by inheriting BindingList in a class that will trigger these events, however the "adding" event doesn't work. The only way I found it working is by overriding EndNew() method, however I don't find a way to get which object is going to be added in this method (if someone has a solution for this, it's ok too!).
So built a totally new class which inherits from same interfaces/class of BindingList and implemented everything (I didn't inherit, however, ICancelAddNew).
I bound it through databindings to my listbox and I find out that nothing works (listchanged events neither listchanging events). How can I simulate BindingList behavior on a listbox?
Any suggestion heavily appreciated, I don't have any other ideas for a workaround
EDIT 1:
This is my collection: http://pastie.org/1978601
And this is how I bind the collection to the ListBox
SpellCasterManager.CurrentProfile.ButtonsMacro.ListChanged += new ListChangedEventHandler(ButtonsMacro_ListChanged);
SpellCasterManager.CurrentProfile.ButtonsMacro.ListChanging += new Expand.ComponentModel.ListChangingEventHandler(ButtonsMacro_ListChanging);
gumpButton.DataBindings.Add("Value", SpellCasterManager.CurrentProfile.ButtonsMacro, "GumpIndex", false, DataSourceUpdateMode.OnPropertyChanged);
Actually under subscribed events there is just a MessageBox.Show("bla");
Your collection won't detect property changes in an existing item because it doesn't hook into the item's property changed events as it is added to the collection.
BindingList<T> does listen to PropertyChanged on your item and does fire a ListChanged event when an item is added to the BindingList and it does include the index at which is is added. Try it in a test app without WinForms.
Adding an existing item is not the same as AddNew(). The AddingNew event is only called when AddNew() is called and allows you to supply the new instance.
When WinForms is involved, things get more complicated. There is the CurrencyManager to think about and also BindingSource. If no events are firing at all then check to see if you are using the CurrencyManager/BindingSource you think you are.
I don't think anything in the framework uses INotifyPropertyChanging, only the original INotifyPropertyChanged. You might want to use Reflector on BindingList to see how the hooking is done and then try to incorporate INotifyPropertyChanging if your item supports it.
Did you follow MSDN guidelines? Your collection class should extend CollectionBase and implement IBindingList - and that should be fine.
Also, you might want your collection item to implement IEditableObject in order to support *Edit operations. This however is not required - more importantly, your collection item should have a way to notify parent collection when it changes (either by following code provided on MSDN, or using for example INotifyPropertyChanged).
You can find working binding sample implementing custom CustomersList on IBindingList doc page (Customer class can be found on IEditableObject doc page).
After getting clear idea of what you are looking for i will suggest following things
Here is a great undo framework which provides lot of functionality.
http://undo.codeplex.com/
Here is sample,
http://blogs.msdn.com/b/kirillosenkov/archive/2009/07/02/samples-for-the-undo-framework.aspx
And in your case, instead of trying to hook on adding/editing events, it's better to track after added/modified/deleted event if you store their initial state. So if the item was removed, in your previous state you will have the item already if you started tracking from the start state of your program.