开发者

Re-ordering a Silverlight Listbox - MVVM-stylee

开发者 https://www.devze.com 2023-02-03 02:19 出处:网络
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 us

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消