在通用 Windows 平台中对 GridView 进行排序

Sorting GridView in Universal Windows Platform

我想对 GridView 中的项目进行排序。

我的 GridView 看起来像:

<GridView x:Name="ivGridView" Margin="70,40,10,10" SelectionChanged="ivGridView_SelectionChanged">
        <GridView.ItemTemplate>
            <DataTemplate>
                <StackPanel Margin="0,0,0,10"  Width="121" Height="128" VerticalAlignment="Top" Background="#19000000">
                    <Image Source="{Binding Image}" VerticalAlignment="Top" Height="88" Margin="0,0,0,0" RenderTransformOrigin="0.5,0.5" >
                        <Image.RenderTransform>
                            <CompositeTransform ScaleX="1.2" ScaleY="1.2"/>
                        </Image.RenderTransform>
                    </Image>
                    <StackPanel Background="{Binding Color}" HorizontalAlignment="Stretch" VerticalAlignment="Bottom">
                        <TextBlock Text="{Binding wpn}" Foreground="White" Margin="10,0,0,0" />
                        <TextBlock Text="{Binding sname}" Foreground="White" Margin="7,0,0,0" FontWeight="Light" />
                    </StackPanel>
                </StackPanel>
            </DataTemplate>
        </GridView.ItemTemplate>

如何对它们进行排序?

您可以对关联的 ItemsSource 进行排序以对视图中的项目进行排序。

除了@Filip的思路,我还会详细介绍如何对GridView中的Item进行排序。

比如你想根据wpn绑定的TextBlock文本的首字母对GridView Items进行排序,那么我们需要定义如下class 首先用于数据绑定:

 public class Test
{
    public BitmapImage Image { get; set; }
    public SolidColorBrush Color { get; set; }
    public string wpn { get; set; }
    public string sname { get; set; }
}

之后我们可以使用ObservableCollection的OrderBy方法将ListView按照wpn列的首字母进行排序,并将ObservableCollection绑定到ItemsSource GridView 如下:

 public ObservableCollection<Test> TestOC = new ObservableCollection<Test>();
    public MainPage()
    {
        this.InitializeComponent();
        TestOC.Add(new Test() {wpn="BB",sname="BBB",Image = new BitmapImage(new Uri("ms-appx:///Capture.PNG")),Color=new SolidColorBrush(Colors.Red)});
        TestOC.Add(new Test() { wpn = "CC", sname = "CCC", Image = new BitmapImage(new Uri("ms-appx:///Capture.PNG")), Color = new SolidColorBrush(Colors.Green) });
        TestOC.Add(new Test() { wpn = "AA", sname = "AA", Image = new BitmapImage(new Uri("ms-appx:///Capture.PNG")), Color = new SolidColorBrush(Colors.Orange) });
        var SortResult = TestOC.OrderBy(a => a.wpn);           
        ivGridView.ItemsSource =SortResult;
    }

结果:

谢谢。