我想用 MVVM 模式对 ListBox 项目进行排序,但以下Behavior
不起作用,你能告诉我哪里错了吗?,有没有使用 MVVM 模式实现的 xceed 列表框示例?
行为
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"/>