Reversed Listbox without sorting

2019-03-02 09:32发布

问题:

I spent last two weeks trying to figure out a method to display the items of a listbox in reversed order without using any sort property and without putting any presentation logic in my entities, I just want that the last inserted item is displayed at the top of the listbox. The only pure XAML solution I've found is this WPF reverse ListView but it isn't so elegant. I've also tried to override the GetEnumerator() of my BindableCollection (I use Caliburn Micro as MVVM framework) to return an enumerator that iterate over my collection's items in the reverse order but id did not work. How can I do?

回答1:

ScaleTransform is an elegant solution to this particular case, but there could be more generic applications (such as binding the same list but with different permutations applied).

It is possible to do this all with converters if you make sure to consider that the binding is to the list, rather than the elements of the list. Assuming that your using an ObservableCollection of strings (sure it would be possible to use generics and reflection to make this more elegant) and missing out all the proper coding of exception handling and multiple calls to Convert...

public class ReverseListConverter : MarkupExtension, IValueConverter
{
    private ObservableCollection<string> _reversedList;

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        return this;
    }

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        _reversedList = new ObservableCollection<string>();            

        var data = (ObservableCollection<string>) value;

        for (var i = data.Count - 1; i >= 0; i--)
            _reversedList.Add(data[i]);

        data.CollectionChanged += DataCollectionChanged;

        return _reversedList;
    }

    void DataCollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
    {                   
        var data = (ObservableCollection<string>)sender;

        _reversedList.Clear();
        for (var i = data.Count - 1; i >= 0; i--)
            _reversedList.Add(data[i]);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}

You can then bind within your XAML with something like

<ListBox ItemsSource="{Binding Converter={ReverseListConverter}}"/>