如何根据条件设置ListView“行”的颜色?

时间:2013-04-24 20:10:05

标签: c# wpf

我最近想出了如何通过添加DataTemplate和静态资源将颜色应用到ListView的GridColumns中的特定项目,以根据其状态有条件地为项目指定颜色。

<StackPanel Orientation="Vertical" Margin="5">
    <Label Content="Tests to Run" FontWeight="Bold" x:Name="TestsToRunLabel"/>
    <ListView ItemsSource="{Binding SelectedTechnician.Tests}"
    SelectedItem="{Binding SelectedTest}" x:Name="AvailableTestsListView" Height="140">
        <ListView.View>
            <GridView>
                <GridViewColumn Header="Id" Width="auto" DisplayMemberBinding="{Binding Id}"/>
                <GridViewColumn Header="Test" Width="auto" DisplayMemberBinding="{Binding TestTypeName}"/>
                <GridViewColumn Header="Method" Width="auto" DisplayMemberBinding="{Binding MethodTypeName}"/>
                <GridViewColumn Header="Customer" Width="auto" DisplayMemberBinding="{Binding CustomerName}"/>
                <GridViewColumn Header="Location" Width="auto" DisplayMemberBinding="{Binding LocationName}"/>
                <GridViewColumn Header="Status" Width="auto">
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding StatusTypeName}"
                                       Foreground="{Binding StatusTypeName, Converter={StaticResource StatusTypeNameToBrushConverter}}"/>
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
            </GridView>
        </ListView.View>
    </ListView>
</StackPanel>

public class StatusTypeNameToBrushConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var statusTypeName = (string) value;
        switch (statusTypeName)
        {
            case "New":
                return Brushes.Blue;
            case "Incomplete":
                return Brushes.Red;
            case "Complete":
                return Brushes.Green;
            default:
                return Brushes.Black;
        }
    }

    public object ConvertBack(
        object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

但是现在我一直想找到一种方法让ListView中的整个“行”基于相同的条件转向那种颜色,但是我找不到一种方法来简化它,因为ListView的GridView是由GridViewColumns并没有一个Row的概念。我唯一可以设置的是TextBlock.Background颜色,它只为“单元格”着色。

所以基本上,我想要的与上面类似:当GridViewColumn包含StatusTypeName为“New”时,将整个行转为蓝色。

我很难过。我怎么能做到这一点?

1 个答案:

答案 0 :(得分:2)

查看此CodeProject文章:

  

http://www.codeproject.com/KB/WPF/HiliteListViewItemsInWPF.aspx

希望这有帮助!