根据其中的值更改 gridviewitem 的颜色(商店 App 8.1)

Change color of gridviewitem based on values in it (store App 8.1)

我想根据 gridviewitem 中包含的文本块中的值更改 gridviewitem 的颜色。

 <GridViewItem x:Name="IdeaGridView" Loaded="IdeaGridView_Loaded"
                         DataContext="{Binding}" Height="150" Width="250" HorizontalAlignment="Left" >
                        <StackPanel Height="150" >
                            <StackPanel Background="#CC00CC" HorizontalAlignment="Left" VerticalAlignment="Top" Width="250" Height="100">
                                <TextBlock Text="{Binding Title}" TextWrapping="Wrap"
                                                   Style="{StaticResource TxtStyle1}" ></TextBlock>
                                <TextBlock Text="{Binding Category}" TextWrapping="Wrap"
                                                   Style="{StaticResource TxtStyle2}" ></TextBlock>

                            </StackPanel>
                            <Grid  Background="Purple" VerticalAlignment="Bottom" Height="50">
                                <StackPanel Orientation="Horizontal" HorizontalAlignment="Left">
                                    <Image Height="20" Width="20"  Source="Assets/phone.png"></Image>
                                    <TextBlock  Style="{StaticResource TxtStyle3}" TextWrapping="Wrap"
                                                                Text="{Binding Type}"></TextBlock>
                                </StackPanel>
                            </Grid>
                        </StackPanel>

                    </GridViewItem>

我想根据 属性 "Category" 的值设置 gridviewitem 的颜色。gridview 有一个对象作为项目源.所以我想根据某些属性更改颜色。有什么建议吗?

您可以创建一个自定义 IValueConverter,它可以将 Category 值转换为颜色。或者,您可以将颜色逻辑移动到 ViewModel 中并直接提供 Color 属性.

这可行:

 class CategoryToColorConverter: IValueConverter
{
  public object Convert(object value, Type targetType, object parameter, string language)
    {
    if((bool)value)
        return Colors.White;
    else
        return Colors.Black;
    }

    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
      if((bool)value)
          return Colors.Black;
             else
          return Colors.White;
    }
}

绑定应该像这样工作:

<Page.Resources>
        <Common:CategoryToColorConverter x:Key="CategoryToColorConverter"/>
</Page.Resources>

...Color={Binding Category,Converter={StaticResource CategoryToColorConverter}}...

希望对您有所帮助!