I want sorting ListBox items with MVVM pattern but following Behavior
doesn't work, Can you please tell me what wrong ?, Is there any sample for xceed listbox implement with MVVM pattern ?
Behavior
public class CollectionViewBehavior : Behavior<Control>
{
public IEnumerable ItemsSource {
get { return (IEnumerable)GetValue(ItemsSourceProperty); }
set { SetValue(ItemsSourceProperty, value); }
}
public static readonly DependencyProperty ItemsSourceProperty =
DependencyProperty.Register("ItemsSource", typeof(IEnumerable), typeof(CollectionViewBehavior), new PropertyMetadata(null, (d, e) => ((CollectionViewBehavior)d).OnItemsSourceChanged()));
CollectionViewSource source;
public ICommand SortAscendingCommand { get; private set; }
public ICommand SortDescendingCommand { get; private set; }
public CollectionViewBehavior() {
source = new CollectionViewSource();
SortAscendingCommand = new DelegateCommand<string>(x => {
source.SortDescriptions.Clear();
source.SortDescriptions.Add(new SortDescription(x, ListSortDirection.Ascending));
});
SortDescendingCommand = new DelegateCommand<string>(x => {
source.SortDescriptions.Clear();
source.SortDescriptions.Add(new SortDescription(x, ListSortDirection.Descending));
});
}
protected override void OnAttached() {
base.OnAttached();
AssociatedObject.SetBinding(Xceed.Wpf.ListBox.ListBox.ItemsSourceProperty, new Binding() { Source = source, Mode = BindingMode.OneWay });
}
protected override void OnDetaching() {
base.OnDetaching();
AssociatedObject.ClearValue(Xceed.Wpf.ListBox.ListBox.ItemsSourceProperty);
}
void OnItemsSourceChanged() {
source.Source = ItemsSource;
}
}
XAML
<xclb:ListBox x:Name="ListBox" ToolPaneVisibility="Collapsed">
<xclb:ListBox.Resources>
<metro:MetroLightThemeResourceDictionary AccentColor="Orange"/>
</xclb:ListBox.Resources>
<i:Interaction.Behaviors>
<local:CollectionViewBehavior x:Name="collectionViewBehavior" ItemsSource="{Binding Items}"/>
</i:Interaction.Behaviors>
</xclb:ListBox>
<Button Command="{Binding ElementName=collectionViewBehavior, Path=SortAscendingCommand}" CommandParameter="ShipCountry"/>