Re-ordering a Silverlight Listbox - MVVM-stylee
I am using RIA services to serve entities to a MVVM-Light enabled Silverlight application.
I have a ViewModel which present a CollectionViewSource of entities to a listbox on the View. The reason I use a CollectionViewSource is so I can control the selected item in the ViewModel; when a new item is created I can create it and then select it for further editing (selecting an item in the listbox enables the editing of that item in a data form).
I need to enable dragdropping for the listbox to allow reordering of the items. I have looked at using the Silverlight Toolkit's ListB开发者_运维问答oxDragDropTarget to enable this functionality but it doesn't work - I assume this is because I need to set the listbox ItemsSource to an ObservableCollection.
If I change the CollectionViewSource in the ViewModel to an ObservableCollection how can I programmatically change the Selected Item of the listbox from the ViewModel?
Any ideas?
You can have a separate property in your ViewModel namely SelectedThing
and bind ListBox.SelectedItem
to it
<ListBox ItemsSource="{Binding TheCollection}" SelectedItem="{Binding SelectedThing}" />
You can wrap your ObservableCollection<T>
within the CollectionViewSource
...as seen here...so that it is the backing collection of data used by the CollectionViewSource
gaining the INotifyCollectionChanged
behavior without losing the benefits from the CollectionViewSource
; which you need for selecting an item.
<UserControl.Resources>
<local:DataSource x:Key="dataSource" />
<CollectionViewSource x:Name="cvs"
Source="{Binding Names, Source={StaticResource dataSource}}">
</CollectionViewSource>
</UserControl.Resources>
...
<ListBox ItemsSource="{Binding Source={StaticResource cvs}}"
Margin="5,5,5,1" Grid.ColumnSpan="4" />
An end to end example from Tim Heuer can be found here which should also help you out in achieving the complete solution.
精彩评论