Reversed Listbox without sorting

我只是一个虾纸丫 提交于 2019-12-02 05:40:23

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}}"/>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!