Grid App 项目模板的 dataItems 的数据模板可在 StandardStyles.xaml 中找到,并由键“Standard250x250ItemTemplate”引用。
如果想法是根据项目的内容改变样式,一种方法可能是使用 Binding.Converter,如此处所示,将相关内容的值转换为所需的样式或样式属性。
例如,如果我想让默认 Grid App 模板中的任何项目在项目编号小于或等于 3 时具有绿色背景,如果高于 3 则具有红色背景,我将创建以下转换器类(在在我的情况下,我刚刚将该类添加到 GroupedItemsPage.xaml.cs,就在 GroupedItemsPage 部分类之前):
// Custom class implements the IValueConverter interface.
public class StyleConverter : IValueConverter
{
#region IValueConverter Members
// Define the Convert method to change a title ending with > 3
// to a red background, otherwise, green.
public object Convert(object value, Type targetType,
object parameter, string language)
{
// The value parameter is the data from the source object.
string title = (string)value;
int lastNum = (int.Parse(title.Substring(title.Length - 1)));
if (lastNum > 3)
{
return "Red";
}
else
{
return "Green";
}
}
// ConvertBack is not implemented for a OneWay binding.
public object ConvertBack(object value, Type targetType,
object parameter, string language)
{
throw new NotImplementedException();
}
#endregion
}
定义类后,连同所需的 Convert 方法,我在 App.xaml 文件中向它添加一个实例,因此它可用于 StandardStyles.xaml 中的项目模板:
<!-- Application-specific resources -->
<local:StyleConverter x:Key="StyleConverter"/>
在 StandardStyles.xaml 中,我制作了 Standard250x250ItemTemplate 的副本,它从项目的 Title 属性绑定到我的转换器类,如下所示:
<DataTemplate x:Key="Standard250x250ItemTemplate_Convert">
<Grid HorizontalAlignment="Left" Width="250" Height="250">
<Border Background="{Binding Title,
Converter={StaticResource StyleConverter}}">
</Border>
<StackPanel VerticalAlignment="Bottom"
Background="{StaticResource ListViewItemOverlayBackgroundThemeBrush}">
<TextBlock Text="{Binding Title}" Foreground="{StaticResource ListViewItemOverlayForegroundThemeBrush}" Style="{StaticResource TitleTextStyle}" Height="60" Margin="15,0,15,0"/>
<TextBlock Text="{Binding Subtitle}" Foreground="{StaticResource ListViewItemOverlaySecondaryForegroundThemeBrush}" Style="{StaticResource CaptionTextStyle}" TextWrapping="NoWrap" Margin="15,0,15,10"/>
</StackPanel>
</Grid>
</DataTemplate>
关键部分是将 Border 元素的 Background 属性绑定到 Title,使用 Converter={StaticResource StyleConverter},它将项目模板连接到我的转换器。请注意,除了绑定 Background 属性之外,我还从项目模板的原始版本中删除了嵌套的 Image 元素。
最后,在 GroupedItemsPage.xaml 中,我将项目模板更改为我的自定义版本:
<!-- Horizontal scrolling grid used in most view states -->
<GridView
x:Name="itemGridView"
...
Padding="116,137,40,46"
ItemsSource="{Binding Source={StaticResource groupedItemsViewSource}}"
ItemTemplate="{StaticResource Standard250x250ItemTemplate_Convert}"
...
ItemClick="ItemView_ItemClick">
完成后,我可以运行该项目,这就是我所看到的:
![带有转换器的网格应用程序](https://i.stack.imgur.com/XE1kK.png)
希望有帮助!
有关 Windows 应用商店应用开发的更多信息,请注册Generation App。