Wpf selecteditem not updating
We’ve also committed to sharing our process, stories, and guidance as we all work together on making the Silverlight ecosystem a better place.
Yesterday a feature request was logged on Code Plex by a customer that would prefer a different behavior for the Auto Complete Box control: they’d prefer that Selected Item not be updated when you press the arrow keys to move through the suggestions list. I went ahead and solved the problem without changing the Auto Complete Box control.
This blog post shows the workaround I came up with.
Suppose you have a collection of Person View Model instances, where the class is defined as: Also suppose that you have these resources set up, and they are applied to the List Box that displays the list of Person View Model objects: The List Box is declared as: The UI also has another List Box that is not bound to a grouped collection view, and also, beneath the List Boxs, a Text Block that shows the selected Person View Model’s Bio property. Because it turns out that the initially selected item in a List Box bound to a grouped ICollection View has its Is Selected property set to true, as a local value.
After making the Items Source change, look through the new collection to see if it contains an item equivalent to the old selected item.
If it does, set this item as the new selected item.
That doesn’t happen very often, but today was one of those days.
(This example view model code assumes that the List View’s Items Source and Selected Item properties are data-bound to equivalently-named properties on the view model and that the view model implements INotify Property Changed.) If the new collection does not contain an entry equivalent to the old selected item, Selected Item will be set to null because Items Source. This responsibility would more appropriately reside in the Account class. However, if other code takes action when Selected Item’s value changes, we still have a problem.
First Or Default(…) returns null when no match is found. In the above code, the view model knows the criteria for determining if two Account object instances represent the same account (“x. If we override Account’s Equals() method to indicate value equivalence, we can remove this knowledge from the view model by changing the search and set line of code to: From the user’s perspective, this approach maintains the selected item. Within the three lines of Update Accounts List(), Selected Item changes from the old selected item, to null, to the new selected item.
I did this by creating a custom selection adapter that is a Content Control.
The adapter modifies the default key down handling logic that ships with the toolkit by ignoring selection updates when the up/down keys are pressed.