如何根据uwp c#中的条件更改gridview行颜色?

时间:2016-08-26 19:01:43

标签: xaml c#-4.0 uwp uwp-xaml

如何根据uwp c#中的条件更改gridview行颜色?

我想根据我的条件突出显示gridview行。

1 个答案:

答案 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 ...>
   <Application.Resources>
      <converters:ItemToColorConverter x:Key="ItemToColorConverter" />
   </Application.Resources>
</Application>

现在在GridViewDataTemplate中使用此转换器:

<GridView ItemsSource="{Binding YourDataSource"}>
   <GridView.ItemTemplate>
      <DataTemplate>
         <Border Background="{Binding Converter={StaticResource ItemToColorConverter}">
            <!-- ... your content -->
         </Border>
      </DataTemplate>
   </GridView.ItemTemplate>
</GridView>