【问题标题】:Sort manually added controls inside ListBox对 ListBox 中手动添加的控件进行排序
【发布时间】:2015-05-14 17:40:33
【问题描述】:

我有一个列表框:

<ListBox Name="LbFrequentColumnItems" Grid.Row="1" MinHeight="0"></ListBox>

我在上面的列表框中添加了许多图像按钮,如下所示:

ImageButton b = new ImageButton();
b.Content = d.DisplayName;              
b.Click += new RoutedEventHandler(OptionalColumnItems_Click);
LbFrequentColumnItems.Items.Add(b);

单击按钮时,我需要按内容排序显示所有图像按钮。

我可以通过复制列表中的所有内容然后排序并再次添加按钮来做到这一点。

但是listbox有没有直接的方法或者方法来执行呢?

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

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

【问题讨论】:

    标签: c# wpf sorting listbox controls


    【解决方案1】:

    您可以按Content 属性对它们进行排序:

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

    它不会抛出InvalidOperationException,因为System.String 实现了IComparable 接口,而(Image)Button 没有实现。

    演示:

    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();
    }
    

    Xaml:

        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <ListBox Name="LbFrequentColumnItems" Grid.Row="0" MinHeight="0"></ListBox>
        <Button Grid.Row="1" Content="Reorder" Click="Button_Click"/>
    

    P.S.: 以同样的方式,您可以将 Button DataContext 属性设置为实现IComparable 的特定数据对象,并按DataContext - new SortDescription("DataContext", ListSortDirection.Ascending) 排序

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-15
      • 2019-07-04
      • 2012-09-29
      • 2020-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-13
      相关资源
      最近更新 更多