C# 对列表框中手动添加的控件进行排序

C# 对列表框中手动添加的控件进行排序,c#,wpf,sorting,listbox,controls,C#,Wpf,Sorting,Listbox,Controls,我有一个列表框: <ListBox Name="LbFrequentColumnItems" Grid.Row="1" MinHeight="0"></ListBox> 单击按钮时,我需要按内容的顺序显示所有图像按钮 我可以通过复制列表中的所有内容,然后进行排序,再添加按钮来完成 但是listbox上有没有直接的方法来执行它呢 我尝试了以下操作,但由于没有任何属性绑定,因此无法正常工作: LbFrequentColumnItems .Items .Sor

我有一个列表框:

<ListBox Name="LbFrequentColumnItems" Grid.Row="1" MinHeight="0"></ListBox>
单击按钮时,我需要按内容的顺序显示所有图像按钮

我可以通过复制列表中的所有内容,然后进行排序,再添加按钮来完成

但是listbox上有没有直接的方法来执行它呢

我尝试了以下操作,但由于没有任何属性绑定,因此无法正常工作:

LbFrequentColumnItems
    .Items
    .SortDescriptions
    .Add(
         new System.ComponentModel.SortDescription("",
            System.ComponentModel.ListSortDirection.Ascending));

您只需按
内容
属性对它们进行排序:

private void Button_Click(object sender, RoutedEventArgs e)
{
    LbFrequentColumnItems
        .Items
        .SortDescriptions
        .Add(new SortDescription("Content", ListSortDirection.Ascending));
}
它不会抛出
InvalidOperationException
,因为
System.String
实现了
IComparable
接口,而
(图像)按钮不实现该接口

演示:

public主窗口()
{
初始化组件();
变量名称=可枚举
.范围(1,10)
.OrderBy(=>Guid.NewGuid())
.选择(i=>
i、 ToString());
foreach(此.CreateNewButtons(名称)中的var按钮)
{
LbFrequentColumnItems.Items.Add(按钮);
}
}
私有IEnumerable CreateNewButtons(IEnumerable名称)
{
foreach(名称中的变量名称)
{
按钮b=新按钮();
b、 内容=名称;
b、 单击+=新建路由EventHandler(可选ColumnItems\u单击);
收益率b;
}
}
private void OptionalColumnItems\u单击(对象发送者、路由目标)
{
抛出新的NotImplementedException();
}
Xaml:


p.S.:同样,您可以将Button DataContext属性设置为实现
IComparable
的特定数据对象,并按
DataContext
-
new SortDescription(“DataContext”,ListSortDirection.升序)

p.S.1:虽然手动添加按钮并不是禁止的,但使用WPF的高级数据绑定和模板功能要好得多。经过一些初始投资后,它们将使应用程序更易于开发和修改

private void Button_Click(object sender, RoutedEventArgs e)
{
    LbFrequentColumnItems
        .Items
        .SortDescriptions
        .Add(new SortDescription("Content", ListSortDirection.Ascending));
}
public MainWindow()
{
    InitializeComponent();

    var names = Enumerable
        .Range(1, 10)
        .OrderBy(_ => Guid.NewGuid())
        .Select(i =>
            i.ToString());

    foreach (var button in this.CreateNewButtons(names))
    {
        LbFrequentColumnItems.Items.Add(button);                
    }
}

private IEnumerable<Button> CreateNewButtons(IEnumerable<String> names)
{
    foreach (var name in names)
    {
        Button b = new Button();
        b.Content = name;
        b.Click += new RoutedEventHandler(OptionalColumnItems_Click);

        yield return b;
    }
}

private void OptionalColumnItems_Click(object sender, RoutedEventArgs e)
{
    throw new NotImplementedException();
}
    <Grid.RowDefinitions>
        <RowDefinition/>
        <RowDefinition/>
    </Grid.RowDefinitions>
    <ListBox Name="LbFrequentColumnItems" Grid.Row="0" MinHeight="0"></ListBox>
    <Button Grid.Row="1" Content="Reorder" Click="Button_Click"/>