我的网格中有一个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
}
}
答案 0 :(得分:2)
我建议使用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 intro
,我还建议您阅读以下内容