WhatTheCode
WhatTheCode

Reputation: 57

Change the text color of a listviewitem in WPF, based on the value of another ListviewItem in the same row

I'd like to change the text color of the "Bedrag" Textblock item to either green or red, based on the value of the first character of the "MarID" listview item in the same row.

When the first character of marID equals 1, the text color should be green, and when it equals 2, the text color should be red.

I've got the following code in my .xaml file:

<ListView x:Name="lstVerrichtingen" HorizontalAlignment="Left" Height="344" Margin="35,28,0,0" VerticalAlignment="Top" Width="934">
   <ListView.View>
      <GridView>
         <GridViewColumn x:Name="gridcolumnVerrichtingID" Header="VerrichtingID" Width="100" DisplayMemberBinding="{Binding VerrichtingID}"/>
         <GridViewColumn x:Name="gridcolumnDatum" Header="Datum" Width="100" DisplayMemberBinding="{Binding Datum, StringFormat={}\{0:dd/MM/yyyy\}}"/>
         <GridViewColumn x:Name="gridcolumnMarID" Header="MarID" Width="75" DisplayMemberBinding="{Binding MarId}"/>
         <GridViewColumn x:Name="gridcolumnBedrag" Header="Bedrag" Width="100" >
            <GridViewColumn.CellTemplate>
               <DataTemplate>
                  <TextBlock Text="{Binding Bedrag, StringFormat={}{0:0.00}}" TextAlignment="Right" Foreground=""/>
               </DataTemplate>
            </GridViewColumn.CellTemplate>
         </GridViewColumn>
         <GridViewColumn x:Name="gridcolumnVanAan" Header="VanAan" Width="100" DisplayMemberBinding="{Binding VanAan}"/>
         <GridViewColumn x:Name="gridcolumnRekeningNummer" Header="Rekeningnummer" Width="100" DisplayMemberBinding="{Binding RekeningNummer}"/>
      </GridView>
   </ListView.View>
</ListView>

How can I solve this problem? Thank you.

Upvotes: 0

Views: 551

Answers (1)

AJITH
AJITH

Reputation: 1175

You can check the MarId binding value using a DataTrigger.

Edit:- I noticed now that you want to check the starting char of the MarId. This can be probably done by a Converter. But by creating a property which returns the first char, you can achieve the same.

    public char FirstIDChar
    {
        get
        {
            return MarID.ToString().First();
        }
    }

And your xaml:

<TextBlock.Style>
    <Style TargetType="TextBlock">
        <Style.Triggers>
            <DataTrigger Binding="{Binding FirstIDChar}" Value="1">
                <Setter Property="Foreground" Value="Red"/>
            </DataTrigger>
            <DataTrigger Binding="{Binding FirstIDChar}" Value="2">
                <Setter Property="Foreground" Value="Green"/>
            </DataTrigger>
        </Style.Triggers>
    </Style>
</TextBlock.Style>

Upvotes: 1

Related Questions