Xceed ListBox排序项使用MVVM模式

时间:2015-01-20 12:23:44

标签: c# wpf mvvm listbox xceed

我希望使用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"/>

0 个答案:

没有答案