2

这是我第一个使用 XAML 的 win 8 商店应用程序,所以有点不确定。我想将数据绑定到gridview。为此,我有一个

class Category
{
    public int Id { get; set; }
    public string CategoryName { get; set; }
    public string IconPath { get; set; }
}

在后面的代码中,我有

protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
    {
        // TODO: Assign a bindable collection of items to this.DefaultViewModel["Items"]
        Model.Utility util = new Utility();
        var categories = util.GetCategoryList(); // this returns List<Category>
        this.DefaultViewModel["Items"] = categories;
    }

我的xaml是:

  <!-- Horizontal scrolling grid used in most view states -->
    <GridView
        x:Name="itemGridView"
        AutomationProperties.AutomationId="ItemsGridView"
        AutomationProperties.Name="Items"
        TabIndex="1"
        Grid.RowSpan="2"
        Padding="116,136,116,46"
        ItemsSource="{Binding Source={StaticResource itemsViewSource}}"
        ItemTemplate="{StaticResource Standard250x250ItemTemplate}"
        SelectionMode="None"
        IsSwipeEnabled="false"/>

但是当我运行应用程序时,我没有看到任何数据。我在哪里做错了?

4

2 回答 2

4

Standard250x250ItemTemplate 默认绑定到属性 Title、SubTitle 和 Image。除非您更新了模板,否则您的 Category 类没有这些属性,而 ItemTemplate 没有任何可显示的内容。我怀疑当您调试应用程序时出现数据绑定错误 VS 说找不到 Title、SubTitle 和 Image 属性。

要更正此问题,请右键单击 GridView,选择 Edit Additonal Templates,Edit Generated Items (ItemTemplate),Edit a Copy 并更新模板以将正确的元素绑定到类上的属性名称。

于 2013-02-19T15:55:52.847 回答
1

根据您代码中的一些名称,您似乎正在尝试为 Grid App 模板重用一些模板代码。

我还将假设您在同一个 XAML 文件中定义了以下资源:

    <CollectionViewSource x:Name="itemsViewSource" Source="{Binding Items}" />

如果是这样,您应该看到每个类别的矩形,但没有数据。那是因为您正在引用Standard250x250ItemTemplate数据模板(在 StandardStyles.xaml 中),并且它正在您的数据源中查找名称为 和 的特定Title字段Subtitle。但是对于类别,您有CategoryNameId

试试这个,看看你的数据是否出现。这上面没有任何样式,但是您可以从中复制样式Standard250x250ItemTemplate并根据需要进行调整。您可以通过 IDE(Blend 或 Visual Studio)执行此操作,无需剪切和粘贴 XAML。

<GridView
    x:Name="itemGridView"
    AutomationProperties.AutomationId="ItemsGridView"
    AutomationProperties.Name="Items"
    TabIndex="1"
    Grid.RowSpan="2"
    Padding="116,136,116,46"
    ItemsSource="{Binding Source={StaticResource itemsViewSource}}"

    SelectionMode="None"
    IsSwipeEnabled="false">

    <GridView.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding CategoryName}" />
        </DataTemplate>
    </GridView.ItemTemplate>
</GridView>
于 2013-02-19T16:27:30.260 回答