如何根据uwp c#中的条件更改gridview行颜色?
我想根据我的条件突出显示gridview行。
答案 0 :(得分:1)
执行此操作的便捷方法是在GridViewItem
周围放置边框,并使用ValueConverter
根据当前项目选择背景颜色。
首先定义值转换器:
public class ItemToColorConverter: IValueConverter
{
//this converts the item from your data source to the color brush
//of the background of the row
public object Convert(object value, Type targetType,
object parameter, string language)
{
//cast the value parameter to the type of item in your data source
var yourValue = ( YourType )value;
if ( yourValue > 10 ) //some condition you want to use to choose the color
{
//highlight
return new SolidColorBrush( Colors.Green );
}
else
{
//leave no background
return new SolidColorBrush( Colors.Transparent );
}
}
//you don't have to implement conversion back as this is just one-way binding
public object ConvertBack(object value, Type targetType,
object parameter, string language)
{
throw new NotImplementedException();
}
}
现在您需要在App.xaml
:
<Application ...>
<Application.Resources>
<converters:ItemToColorConverter x:Key="ItemToColorConverter" />
</Application.Resources>
</Application>
现在在GridView
项DataTemplate
中使用此转换器:
<GridView ItemsSource="{Binding YourDataSource"}>
<GridView.ItemTemplate>
<DataTemplate>
<Border Background="{Binding Converter={StaticResource ItemToColorConverter}">
<!-- ... your content -->
</Border>
</DataTemplate>
</GridView.ItemTemplate>
</GridView>