按字母顺序排列StackPanel中的元素

本文关键字:元素 StackPanel 排列 顺序 | 更新日期: 2023-09-27 18:16:08

我有一个StackPanel在我的网格,它显示一个动态生成的按钮列表,我试图找出如何让他们按字母顺序升序显示。

XAML代码
<StackPanel Grid.Column="0" Name="AreaStackPanel" Orientation="Vertical" Background="Khaki">
</StackPanel>
<StackPanel  Grid.Column="1"  Orientation="Horizontal" Background="Beige">
    <GroupBox Name="StatusGroupBox" Header="Work Items" Width="234">
        <StackPanel Name="StatusStackPanel"></StackPanel>
    </GroupBox>
</StackPanel>

c#代码
private void LoadExistingAreas()
{
    List<string> collections = Reporter.GetCollections();
    string unique = "";
    foreach (string collection in collections)
    {
        string areaName = Path.GetFileName(collection);
        if (unique.Contains(areaName)) continue;
        unique += areaName;
        Button areaButton = new Button();
        areaButton.Click += areaButton_Click;
        areaButton.Margin = new Thickness(2);
        areaButton.Content = areaName;
        AreaStackPanel.Children.Add(areaButton);
        Area
    }
}

按字母顺序排列StackPanel中的元素

我建议使用MVVM来完成此任务。我在这里发布了一个例子,说明如何以一种相当干净的方式工作。

您的XAML应该如下所示:

<Window x:Class="ItemTemplateDemo.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:ItemTemplateDemo"
    Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
    <local:MainViewModel/>
</Window.DataContext>
<Grid>
    <ItemsControl ItemsSource="{Binding ButtonDescriptions}">
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <StackPanel></StackPanel>
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <Button Margin="2" Content="{Binding Name}" Command="{Binding OnClickCommand}"></Button>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
</Grid>

主视图模型。您还应该对这里的数据进行排序和筛选

 public class MainViewModel
{
    public ObservableCollection<ButtonDescription> ButtonDescriptions { get; private set; }
    public MainViewModel()
    {
        ButtonDescriptions = new ObservableCollection<ButtonDescription>();
        for (int i = 0; i < 10; i++)
        {
            var bd = new ButtonDescription() { Name = "Button " + i };
            ButtonDescriptions.Add(bd);
        }
    }
}

按钮描述包含按钮的属性

    public class ButtonDescription
{
    private string name;
    public string Name
    {
        get { return name; }
        set { name = value; }
    }
    private ICommand onClickCommand;
    public ICommand OnClickCommand
    {
        get { return onClickCommand; }
        set { onClickCommand = value; }
    }
    public ButtonDescription()
    {
    }
}

如果你不熟悉MVVM,我还建议你阅读下面的MVVM介绍