如何根据单个项目的属性设置单个网格项目的背景颜色?我有以下代码:
<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
属性,我想使用该属性来设置颜色,如果为true,则为灰色,否则用户会加重颜色。
最佳答案
例如,您可以将Converter用于此任务:
在 namespace 中定义转换器类:
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;
}
}
}
然后在XAML中的Page.Resources中定义一个键(不要忘记添加 namespace ):
<Page ...
... some code ...
xmlns:converter="MyConverters"
.../>
<Page.Resources>
<converter:BoolToBrush x:Key="BoolToBrush"/>
</Page.Resources>
最后,您可以将转换器与Binding一起使用:
<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>
关于c# - 基于项目属性的网格背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24595658/