网格视图中的数据绑定
本文关键字:数据绑定 视图 网格 | 更新日期: 2023-09-27 18:31:01
我正在尝试将一些数据绑定到 Windows 8.1 Hub
控件中的GridView
。
目前,我在Page.Resources
下设置了一个DataTemplate
,如下所示:
<DataTemplate x:Key="Standard240x320ItemTemplateFAV">
<Grid HorizontalAlignment="Left" Width="320" Height="240">
<Border Background="{StaticResource ListViewItemPlaceholderBackgroundThemeBrush}">
<Image Source="{Binding FavImage}" Stretch="UniformToFill"/>
</Border>
<StackPanel VerticalAlignment="Bottom" Background="{StaticResource ListViewItemOverlayBackgroundThemeBrush}">
<TextBlock Text="{Binding FavTitle}" Foreground="{StaticResource ListViewItemOverlayForegroundThemeBrush}" Style="{StaticResource TitleTextBlockStyle}" Height="48" Margin="15,0,15,0"/>
</StackPanel>
</Grid>
</DataTemplate>
然后我有这个HubSection
:
<HubSection x:Name="FavHub" Padding="40,60,40,0" >
<DataTemplate>
<GridView
x:Name="itemGridView"
Margin="-4,-4,0,0"
AutomationProperties.AutomationId="ItemGridView"
AutomationProperties.Name="Items In Group"
ItemsSource="{Binding Items}"
ItemTemplate="{StaticResource Standard240x320ItemTemplateFAV}"
SelectionMode="Single"
IsSwipeEnabled="false"
IsItemClickEnabled="True"
ItemClick="ItemView_ItemClick">
</GridView>
</DataTemplate>
</HubSection>
我使用此代码添加数据上下文:
FavHub.DataContext = new FavData(Constants.getImage("1002"), "No Favourites");
其中 FavData 类是:
public class FavData
{
public static string FavImage { get; set; }
public static string FavTitle { get; set; }
public FavData() { }
public FavData(string itemImageSet, string itemNameSet)
{
FavImage = itemImageSet;
FavTitle = itemNameSet;
}
}
但是,中心部分中未显示任何数据。我做错了什么?
您需要
将列表(如List<FavData>
或ObservableCollection<FavData>
)绑定到 Hub。
现在,您有一个GridView
,其中包括 ItemsSource
属性的初始化。此属性用作项列表的源。
<GridView x:Name="itemGridView"
ItemsSource="{Binding Items}"
</GridView>
绑定指定为 {Binding Items}
这意味着对于当前绑定到 Hub 的任何对象,获取存储在 Items
属性上的 List。由于您当前已通过 DataContext
属性将单个 FavData
实例设置为 Hub,并且它没有名为 Items
的属性,因此没有任何要显示的内容。
因此,我的建议是创建一个FavData
实例列表并将其绑定到 Hub 实例。如果要直接绑定列表而不是将列表存储在另一个"父"对象中,则还需要调整Binding
以引用"self"而不是特定属性。为此,您只需使用语法:{Binding}
。它的意思只是,"绑定到我。因此,GridView 将直接在绑定对象上查找项列表(FavData
列表)。
<GridView x:Name="itemGridView"
ItemsSource="{Binding}"
</GridView>
在 C# 中:
List<FavData> favs = new List<FavData>();
favs.Add(new FavData(Constants.getImage("1002"), "No Favourites"));
FavHub.DataContext = favs;