基于Item属性的网格背景颜色

时间:2014-07-06 12:09:00

标签: c# xaml mvvm windows-phone-8.1

如何根据单个项目的属性设置各个网格项目的背景颜色?我有以下代码:

<PivotItem x:Uid="PivotBlocks" Margin="10, 10, 10, 10" Header="blockx" DataContext="{Binding Blocks}" d:DataContext="{Binding , Source={d:DesignData Source=/DataModel/SampleData.json, Type=data:DataSource}}">
    <GridView ItemsSource="{Binding Formations}" IsItemClickEnabled="True" ItemClick="Point_ItemClick" Loaded="PivotBlocks_Loaded" ContinuumNavigationTransitionInfo.ExitElementContainer="True">
        <GridView.ItemTemplate>
            <DataTemplate>
                <Grid Width="80" Height="80" Margin="0,0,10,10" Background="{StaticResource PhoneAccentBrush}">
                    <StackPanel VerticalAlignment="Bottom">
                        <TextBlock Text="{Binding Shorthand}" Padding="5, 0, 0, 5" Style="{StaticResource SubheaderTextBlockStyle}" />
                    </StackPanel>
                </Grid>
            </DataTemplate>
        </GridView.ItemTemplate>
    </GridView>
</PivotItem>

每个阵型(项目)都有HasBeenSelected类型Bool的属性,我想用它来设置颜色,如果为真则为灰色,否则用户强调颜色。

1 个答案:

答案 0 :(得分:1)

例如,您可以使用 Converter 执行此任务:

在命名空间中定义转换器类:

namespace MyConverters
{
  public class BoolToBrush : IValueConverter
  {
    private Brush FalseValue = new SolidColorBrush(Colors.Gray);
    public Brush TrueValue = Application.Current.Resources["PhoneAccentBrush"] as Brush;

    public object Convert(object value, Type targetType, object parameter, string language)
    {
        if (value == null) return FalseValue;
        else return (bool)value ? TrueValue : FalseValue;
    }

    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        return value != null ? value.Equals(TrueValue) : false;
    }
  }
}

然后在 Page.Resources 中的XAML中定义一个键(不要忘记添加命名空间):

<Page ...
      ... some code ...
 xmlns:converter="MyConverters"
      .../>
<Page.Resources>
    <converter:BoolToBrush x:Key="BoolToBrush"/>
</Page.Resources>

然后最后你可以使用你的转换器绑定:

<PivotItem x:Uid="PivotBlocks" Margin="10, 10, 10, 10" Header="blockx" DataContext="{Binding Blocks}" d:DataContext="{Binding , Source={d:DesignData Source=/DataModel/SampleData.json, Type=data:DataSource}}">
    <GridView ItemsSource="{Binding Formations}" IsItemClickEnabled="True" ItemClick="Point_ItemClick" Loaded="PivotBlocks_Loaded" ContinuumNavigationTransitionInfo.ExitElementContainer="True">
        <GridView.ItemTemplate>
            <DataTemplate>
                <Grid Width="80" Height="80" Margin="0,0,10,10" Background="{Binding HasBeenSelected, Converter={StaticResource BoolToBrush}}">
                    <StackPanel VerticalAlignment="Bottom">
                        <TextBlock Text="{Binding Shorthand}" Padding="5, 0, 0, 5" Style="{StaticResource SubheaderTextBlockStyle}" />
                    </StackPanel>
                </Grid>
            </DataTemplate>
        </GridView.ItemTemplate>
    </GridView>
</PivotItem>