-2

我需要通过 wpf 中 listboxitem 的 sSelected 属性对所有项目进行排序。我怎样才能做到这一点?

4

1 回答 1

0

不清楚你的项目是什么,所以我将使用整数。这个想法是用户将选择项目,按下按钮将启动排序,所选项目将被排序,放置在列表的开头,然后将未选择的项目添加到新排序的项目之后。

xml:

<StackPanel Orientation="Vertical">
    <ListBox Name="lbData" SelectionMode="Multiple"/>
    <Button Click="Button_Click" Height="20"/>
</StackPanel>

后面的 C# 代码

public MainWindow()
{
    InitializeComponent();

    lbData.ItemsSource = new List<int> {1, 7, 2, 4, 10};

}

private void Button_Click(object sender, RoutedEventArgs e)
{
    var selected = lbData.SelectedItems
                         .OfType<int>()
                         .ToList();
    if (selected.Any())
    {
        // Remove the items
        var diff = lbData.ItemsSource
                         .OfType<int>()
                         .Except(selected);

        // Sort the selected and place them at the beginning
        var ordered = selected.OrderBy(itm => itm).ToList();

        ordered.AddRange(diff);

        lbData.ItemsSource = ordered;
    }
}
于 2013-10-14T18:59:29.647 回答