Friday, February 20, 2015

WPF Data Binding

Example: Binding Sorted ObservableCollection to an ItemControl-Derived Control

ObservableCollection<LookupListItem> lookupList =  DataCache.GetLookupList();

CollectionViewSource collectionViewSource = new CollectionViewSource();
collectionViewSource.SortDescriptions.Add(new
  System.ComponentModel.SortDescription("ItemName",
  System.ComponentModel.ListSortDirection.Ascending));

collectionViewSource.Source = lookupList;
this.DataContext = collectionViewSource; // sorted data

Set ItemSource of the ItemsControl-derived control (combobox in this case)
to {Binding} so that the control gets the sorted data from the DataContext
which holds the sorted CollectionViewSource:

<ComboBox x:Name="theList" Grid.Column="0"
  DisplayMemberPath="ItemName" ItemsSource="{Binding}"/>