I am trying to synchronize the selected tab item of a WPF tab control with the last item that was added.
Since there is no such property as e.g. IsSynchedWithLastAddedItem, I am trying to detect when an item was added in order to point the SelectedItem at the last added one.
I cannot find the event that gets raised - either on the tab control or its Items, when a TabItem was added.
I am sure something like it must exist though, so I hope someone can help me out.
var view=CollectionViewSource.GetDefaultView(m_tabControl.ItemsSource);
view.CollectionChanged+=(o,e)=>{/*Here your code*/};
If you work directly with the Items-collection, the same technique will work also. Get the default CollectionViewSource for this collection.
var view=CollectionViewSource.GetDefaultView(m_tabControl.Items);
view.CollectionChanged+=(o,e)=>{/*Here your code*/};
As Timores wrote, for the m_tabControl.Items-property, you can attach a handler directly. The same is also true for most ItemsSource-references, but there you have to check yourself for the INotifyCollectionChanged-interface.
I have not tested it. Make a comment if it does not work.
The Items collection is of type ItemCollection, which derives from CollectionView which implements INotifyCollectionChanged. So you could listen to CollectionChanged and get to know when an item is added.
Don't know how to do that in XAML, though.
Related
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
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 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.
I am having trouble setting the Selected Item of a Listbox I am populating and adding to the LayoutRoot's children in code.
I am creating the ListBox over when going back to the page, so I am saving a variable which will tell me what the selected item was before the user clicked.
I tried setting SelectedIndex, but that did not seem to work. That selects the item and calls SelectionChanged, but the item does not come into focus.
I also tried the combination of MyListBox.ScrollIntoView(MyListBox.Items[MyListBox.SelectedIndex]) and MyListBox.UpdateLayout(), but that did not seem to work either. The item does not seem to come into focus.
Try MyListBox.SelectedItem.EnsureVisible().
(If it doesn't have SelectedItem (ListBox on the desktop CLR doesn't), then use SelectedItems[0] instead)
E: Okay, looks like Windows Phone doesn't support that. However, it does support MyListBox.EnsureVisible(MyListBox.SelectedItems[0])
I ended up fixing this by Adding the UserControl that had the ListBox into the Page's XAML, and the ListBox into the UserControl's XAML.
Then, I was able to use the ScrollIntoView(MyListBox.Items[mySavedSelectedItem]);
I simply saved this value when the user made the selection.
mySavedSelectedItem = ((ListBox)sender).SelectedIndex;
I have a render-heavy item template in an ItemsControl and want to minimize the recreation of child item templates when ItemsSource signals a change. I am wondering if, because ObservableCollection can tell WPF precisely what has changed (as opposed to just the whole list), if it is more efficient in rendering changes to the collection, or if WPF is smart enough to reuse previous item views if it detects the same item is still in the changed list.
Your suspicion is correct. WPF will not reuse previous views. If you replace the ItemsSource of an ItemsControl with a new List, it will create completely new views for each item in the list, even if the same items were in the old list.
You can test this yourself by putting a custom control in the ItemTemplate and adding a breakpoint or debug logging to its constructor. If you replace the ItemsSource with an identical list, you will see your control constructed once for each item in the list. On the other hand, when an item is added to an ObservableCollection you will only see it called once.
Note that the ItemsControl can reuse the container (such as ListBoxItem) if you are using a virtualizing panel and have container recycling enabled. See Link. It still can't reuse the contents of the container, however.
ObservableCollection only informs of addition and removal of objects - so perhaps not as precise as what you were expecting (if an object within the list changes, ObservableCollection will not fire off any notifications).