gpt4 book ai didi

c# - WPF 排序子集合

转载 作者:太空宇宙 更新时间:2023-11-03 14:00:36 25 4
gpt4 key购买 nike

我有一个要在 ItemsControl 中显示的项目集合。这些项目中的每一个都会有一个子项目的集合,这些子项目应该在每个项目内水平显示。我的问题是如何在 XAML 中对子项进行排序?我通常会使用 CollectionViewSource,但在这种情况下无法正常工作。下面是一个简单的例子。在这种情况下,somedata 是我的项目集合(字符串),项目是字符集合。我只想修改此示例,以便每一行都对所有字符进行排序。

这是一个窗口的构造函数:

        string[] somedata = new string[] { "afkhsdfgjh", "fsdkgjhsdfjh", "sdfjhdfsjh" };
mainList.ItemsSource = somedata;

这就是 XAML(在 Window 标签内)

<ItemsControl Name="mainList">
<ItemsControl.ItemTemplate>
<DataTemplate>
<ItemsControl ItemsSource="{Binding}" >
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"></StackPanel>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemContainerStyle>
<Style TargetType="ContentPresenter">
<Setter Property="Margin" Value="0,0,5,0"></Setter>
</Style>
</ItemsControl.ItemContainerStyle>
</ItemsControl>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>

最佳答案

您也可以将 CollectionViewSource 用于子项。这是示例 View 模型:

public class Item : ViewModel
{
public String Name
{
get { return name; }
set
{
if (name != value)
{
name = value;
OnPropertyChanged("Name");
}
}
}
private String name;

public ObservableCollection<String> SubItems
{
get
{
return subItems ?? (subItems = new ObservableCollection<String>());
}
}
private ObservableCollection<String> subItems;
}

...和标记:

<ListBox ItemsSource="{Binding}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<StackPanel.Resources>
<CollectionViewSource Source="{Binding SubItems}" x:Key="subItemsViewSource">
<CollectionViewSource.SortDescriptions>
<scm:SortDescription Direction="Ascending" />
</CollectionViewSource.SortDescriptions>
</CollectionViewSource>
</StackPanel.Resources>
<TextBlock Text="{Binding Name}" />
<ListBox ItemsSource="{Binding Source={StaticResource subItemsViewSource}}">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"></StackPanel>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
</ListBox>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>

在后面的代码中用一些数据初始化数据上下文:

    public MainWindow()
{
InitializeComponent();
DataContext = new ObservableCollection<Item>
{
new Item
{
Name = "John",
SubItems =
{
"Mary", "Peter", "James"
},
},
new Item
{
Name = "Homer",
SubItems =
{
"Lisa", "Bart", "Marge"
},
}
};
}

诀窍是将描述 CollectionViewSource 的资源放入主列表项的布局控件的资源中。

关于c# - WPF 排序子集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10810284/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com