我希望使用MVVM模式对ListBox项进行排序,但是Behavior
之后没有工作,你能告诉我什么是错的吗?是否有任何针对具有MVVM模式的xceed listbox实现的示例?
行为
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"/>