views:

203

answers:

1

I've got two Silverlight 4.0 ComboBoxes; the second displays the children of the entity selected in the first:

<ComboBox 
    Name="cmbThings"
    ItemsSource="{Binding Path=Things,Mode=TwoWay}"
    DisplayMemberPath="Name"
    SelectionChanged="CmbThingsSelectionChanged" />
<ComboBox 
    Name="cmbChildThings"
    ItemsSource="{Binding Path=SelectedThing.ChildThings,Mode=TwoWay}"
    DisplayMemberPath="Name" />

The code behind the view provides a (simple, hacky) way to databind those ComboBoxes, by loading Entity Framework 4.0 entities through a WCF RIA service:

public EntitySet<Thing> Things { get; private set; }
public Thing SelectedThing { get; private set; }

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    var context = new SortingDomainContext();
    context.Load(context.GetThingsQuery());
    context.Load(context.GetChildThingsQuery());
    Things = context.Things;            
    DataContext = this;
}

private void CmbThingsSelectionChanged(object sender, SelectionChangedEventArgs e)
{
    SelectedThing = (Thing) cmbThings.SelectedItem;
    if (PropertyChanged != null)
    {
        PropertyChanged.Invoke(this, new PropertyChangedEventArgs("SelectedThing"));
    }
}

public event PropertyChangedEventHandler PropertyChanged;

What I'd like to do is have both combo boxes sort their contents alphabetically, and I'd like to specify that behaviour in the XAML if at all possible.

Could someone please tell me what is the idiomatic way of doing this with the SL4 / EF4 / WCF RIA technology stack?

A: 

Try to use a CollectionViewSource and bind this to your combobox. The CollectionViewSource provides sorting, grouping and filtering.

As Source for your CollectionViewSource set your EntitySet. The CollectionViewSource can be added to the Resources-Section of any control.

<CollectionViewSource Source="{StaticResource Things}" x:Key="cvs"> <!--The source can be set in procedural code-->
  <CollectionViewSource.SortDescriptions>
    <scm:SortDescription PropertyName="Name"/> <!--The name of the property to sort items-->
  </CollectionViewSource.SortDescriptions>
</CollectionViewSource>

<!--The prefix scm mappes to the System.ComponentModel-->

I didn´t tested it, but it should work. The Property Source of the CollectionViewSource is of type object. Don´t know if that object needs to implement a specified interface, such as IEnumerable.

Jehof
Thanks - there's a quick tutorial on CollectionViewSource here too: http://bea.stollnitz.com/blog/?p=17
Duncan Bayne