在ListBox中对ObservableCollection <Class>数据进行排序

时间:2019-11-24 04:22:51

标签: c# wpf linq sorting listbox

我的程序有两个ListBoxes。他们通过AddRemove按钮彼此交换项目。在添加和删除期间,我想使用OrderBy对项目进行排序(按ID),但我不知道如何使用此查询结果。我该如何使用OrderBy

enter image description here

似乎OrderBy在起作用,但我只是不知道放在哪里:

IEnumerable<GraphViewModel> query_orderBy_ID = RightListBoxItems.OrderBy(value => value.ID);
??? = query_orderBy_ID;

...好,然后我将右侧放回原始收藏中:

RightListBoxItems = (ObservableCollection<GraphViewModel>)RightListBoxItems.OrderBy(value => value.ID).ToList();
  

错误CS0030:无法转换类型   'System.Collections.Generic.List'   至   'System.Collections.ObjectModel.ObservableCollection'

我认为强制转换可以解决此问题,但不起作用。

这是我的代码:

MainWindow.xaml.cs

已编辑:对不起,query_orderBy_IDAdd_Button_Click()中添加了一个using Sorting_List_with_OrderBy.ViewModel; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Windows; namespace Sorting_List_with_OrderBy { public partial class MainWindow : Window { public ObservableCollection<GraphViewModel> LeftListBoxItems { get; set; } = new ObservableCollection<GraphViewModel>(); public ObservableCollection<GraphViewModel> RightListBoxItems { get; set; } = new ObservableCollection<GraphViewModel>(); ObservableCollection<string> TestItems = new ObservableCollection<string>(); IEnumerable<GraphViewModel> query_orderBy_ID; public MainWindow() { InitializeComponent(); DataContext = this; TestItems.Add("T0"); TestItems.Add("T1"); TestItems.Add("T2"); foreach (var test in TestItems.Select((k, i) => new { kvp = k, index = i })) { LeftListBoxItems.Add(new GraphViewModel(test.index, test.kvp)); } } private void Add_Button_Click(object sender, RoutedEventArgs e) { foreach (var graphViewModel in LeftListBox.SelectedItems.Cast<GraphViewModel>().ToList()) { LeftListBoxItems.Remove(graphViewModel); // 1st Attempt: I don't know where to put this result to ... query_orderBy_ID = RightListBoxItems.OrderBy(value => value.ID); // 2nd Attempt: This substitution fails ... //RightListBoxItems = (ObservableCollection<GraphViewModel>)RightListBoxItems.OrderBy(value => value.ID).ToList(); RightListBoxItems.Add(graphViewModel); } query_orderBy_ID = RightListBoxItems.OrderBy(value => value.ID); foreach (GraphViewModel orderBy_ID in query_orderBy_ID) { MessageBox.Show(orderBy_ID.ID + ": " + orderBy_ID.TestName); } } private void Remove_Button_Click(object sender, RoutedEventArgs e) { foreach (var graphViewModel in RightListBox.SelectedItems.Cast<GraphViewModel>().ToList()) { RightListBoxItems.Remove(graphViewModel); LeftListBoxItems.Add(graphViewModel); } } } } 循环,

<Window x:Class="Sorting_List_with_OrderBy.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:Sorting_List_with_OrderBy"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="600">
    <Grid>
        <ListBox Margin="15,158,0,69.8" x:Name="LeftListBox" HorizontalAlignment="Left" Width="184" Background="AntiqueWhite"
                 SelectionMode="Extended" ItemsSource="{Binding LeftListBoxItems}" DisplayMemberPath="TestName"/>

        <Button x:Name="Add_Button" Height="26" Margin="232,196,0,0" HorizontalAlignment="Left" VerticalAlignment="Top" Width="80"
                 Click="Add_Button_Click" Content="Add &gt;&gt;"/>
        <Button x:Name="Remove_Button" Margin="230,267,0,0" HorizontalAlignment="Left" VerticalAlignment="Top" Width="82"
                 Click="Remove_Button_Click" Height="26" Content="&lt;&lt; Remove"/>

        <ListBox Margin="343,158,0,71.8" x:Name="RightListBox" HorizontalAlignment="Left" Width="200" Background="AntiqueWhite"
                 SelectionMode="Extended" ItemsSource="{Binding RightListBoxItems}" DisplayMemberPath="TestName"/>
    </Grid>
</Window>

MainWindow.xaml

namespace Sorting_List_with_OrderBy.ViewModel
{
    public class GraphViewModel
    {
        public int ID { get; }
        public string TestName { get; }

        public GraphViewModel(int id, string testName) => (ID, TestName) = (id, testName);
    }
}

ViewModel / GraphViewModel.cs

T0

此问题的主要目的是对我的ListBox进行排序,因此应该以正确的顺序[T1T2console.log]对ListBox项进行排序。如果以上问题得到解决,我相信它们会得到解决。

任何建议都会有所帮助。谢谢。

1 个答案:

答案 0 :(得分:1)

OrderBy将返回IOrderedEnumerable<T>,该this.LeftListBoxItems = new ObservableCollection<GraphViewModel>(this.LeftListBoxItems.OrderBy(value => value.ID)) 根据排序键进行排序。原始集合保持其原始状态。因此,您需要使用排序后的结果集合覆盖原始集合:

ObservableCollection

要在添加/删除项目时自动进行SortDescription排序,可以通过在ICollectionView上添加CollectionViewSource.GetDefaultView(this.LeftListBoxItems) .SortDescriptions .Add(new SortDescription(nameof(GraphViewModel.ID), ListSortDirection.Ascending)); 来对其进行一次配置(例如,从构造函数中进行配置):

ICollectionView

注意
WPF绑定到集合的SortDescription,而不是直接绑定到集合。在ICollectionView上设置ICollectionView只会对此 HttpServerResponse res = routingContext.response(); res.setChunked(true); EventBus eventBus = vertx.eventBus(); eventBus.request(InstrumentsServiceVerticle.FETCH_INSTRUMENTS_ADDRESS, "", result -> { if (result.succeeded()) { res.setStatusCode(200).write((Buffer) result.result().body()).end(); } else { res.setStatusCode(400).write(result.cause().toString()).end(); } }); My instrumentVerticle is as follows: static final String FETCH_INSTRUMENTS_ADDRESS = "fetch.instruments.service"; // Reuse the Vert.x Mapper :) private final ObjectMapper mapper = Json.mapper; private final InstrumentService instrumentService; public InstrumentsServiceVerticle(InstrumentService instrumentService) { this.instrumentService = instrumentService; } private Handler<Message<String>> fetchInstrumentsHandler() { return msg -> vertx.<String>executeBlocking(future -> { try { future.complete(mapper.writeValueAsString(instrumentService.getInstruments())); } catch (JsonProcessingException e) { logger.error("Failed to serialize result "+ InstrumentsServiceVerticle.class.getName()); future.fail(e); } }, result -> { if (result.succeeded()) { msg.reply(result.result()); } else { msg.reply(result.cause().toString()); } }); } @Override public void start() throws Exception { super.start(); vertx.eventBus().<String>consumer(FETCH_INSTRUMENTS_ADDRESS).handler(fetchInstrumentsHandler()); } 进行排序。这意味着UI看上去已排序,而基础集合保持未排序(或按不同规则排序)。