Windows Store 动态添加项目到 GridView

Windows Store dynamically add items into GridView

嘻嘻,

我目前正在尝试制作一个 GridView,其中包含图像中的项目和标题的文本块。我想动态添加这些。

搜索了一个小时后,我得到了这个:

<GridView 
    x:Name="grid" 
    SelectionMode="Single" 
    IsItemClickEnabled="False"  
    Foreground="#DEFFFFFF" 
    SelectionChanged="GridView_SelectionChanged" Margin="0, 50, 0, 0" >
    <GridView.Resources>
        <CollectionViewSource x:Name="CollectionViewSource" x:Key="CollectionViewSource" />
        <DataTemplate x:Key="ImageBinder">
            <Image Source="{Binding Photo}" Width="200" Height="200" />
        </DataTemplate>
        <DataTemplate x:Key="TextBinder">
            <TextBlock Text="{Binding Text}" Width="auto" Height ="auto" />
        </DataTemplate>
    </GridView.Resources>

</GridView>

我从阅读中了解到 Source 属性需要 class 之类的东西?但我真的不明白如何以这种方式将 Item 动态添加到网格中,有人可以用代码示例向我解释一下吗?

class 的示例:

Public Class PiecePictureObject{
    Public String [Text] { get; set; }
    Public BitmapImage [Photo] { get; set; }
}
  • 然后创建一个列表 class

  • 向该列表添加元素

  • 影响你的gridview GridviewExample.DataContext = ListYouCreatedOfYourObject

和XAML

<GridView x:Name="grdPiecesImage" ItemsSource="{Binding}" SelectionChanged="grdPiecesImage_SelectionChanged">
    <GridView.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Vertical">
                <StackPanel.Background>
                    <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                        <GradientStop Color="Black"/>
                        <GradientStop Color="#FF443585" Offset="1"/>
                    </LinearGradientBrush>
                </StackPanel.Background>
                <TextBlock Text="{Binding Text}" Height="45" FontSize="25" Padding="10"/>
                <Image Source="{Binding Photo}" Height="95" Width="250"/>
            </StackPanel>
        </DataTemplate>
    </GridView.ItemTemplate>
</GridView>

我建议使用与照片和文本不同的词,例如 PiecePhoto、PieceText

确保绑定中的名称与对象相同。如果您在从文件中获取图像时遇到问题,我在 VB.NET

中就是这样做的
    Public Async Function LoadImage(_folder As StorageFolder, _filename As String) As Task(Of BitmapImage)
        Try
            Dim file = Await _folder.GetFileAsync(_filename)
            Dim bitmapImage As BitmapImage = New BitmapImage()
            Dim stream As FileRandomAccessStream = CType(Await file.OpenAsync(FileAccessMode.Read), FileRandomAccessStream)
            bitmapImage.SetSource(stream)
            Return bitmapImage
        Catch ex As Exception
            Return Nothing
        End Try
    End Function

抱歉给您带来不便,我目前没有时间翻译成 C#

如果您仍有问题,请查看此内容:http://www.c-sharpcorner.com/UploadFile/c25b6d/image-binding-in-gridview-and-listview-in-windows-8-apps-usi/