views:

521

answers:

1

I need to sort the strings in a ListBox, but it is bound to the view model by another component via the DataContext. So I can't directly instantiate the view model in xaml, as in this example, which uses the ObjectDataProvider:

http://www.galasoft.ch/mydotnet/articles/article-2007081301.aspx

in my xaml:

<ListBox ItemsSource="{Binding CollectionOfStrings}" />

in my view model:

public ObservableCollection<string> CollectionOfStrings
{
  get { return collectionOfStrings; }
}

in another component:

view.DataContext = new ViewModel();

there is no code behind!

So using purely xaml, how would I sort the items in the ListBox? Again, the xaml doesn't own the instantiation of the view model.

Thanks!

+6  A: 

Use a CollectionViewSource:

<CollectionViewSource x:Key="SortedItems" Source="{Binding CollectionOfStrings}">
    <CollectionViewSource.SortDescriptions>
        <scm:SortDescription PropertyName="SomePropertyOnYourItems"/>
    </CollectionViewSource.SortDescriptions>
</CollectionViewSource>

<ListBox ItemsSource="{Binding Source={StaticResource SortedItems}}"/>

You might want to wrap your strings in a custom VM class so you can more easily apply sorting behavior.

HTH, Kent

Kent Boogaart
Thanks, Kent! Binding the Source attribute on a CollectionViewSource was the missing link for me. I appreciate it. In this case, I didn't want a custom VM class, so I just left off the PropertyName attribute, which apparently works for string collections just fine.
speedmetal
Also, to any onlookers out there, the SortDescription tag takes a Direction attribute.
speedmetal