user3587624 user3587624 - 1 year ago 156
C# Question

How to change color of text when UI gets updated in WPF MVVM

I have the following XAML

<UserControl x:Class="DomainExperience.Pane.DomainFile.DomainAnalysisPaneResultsControl"
Background="{DynamicResource VsBrush.Window}"
Foreground="{DynamicResource VsBrush.WindowText}"
d:DesignHeight="300" d:DesignWidth="300"

<domainFile:StatusColoredDataTemplateClass x:Key="StatusColoredDataTemplate" />

<RowDefinition Height="*"></RowDefinition>

<ListView Grid.Row="0" ItemsSource="{Binding Path=Results}">

<GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}"/>
<GridViewColumn Header="Status" DisplayMemberBinding="{Binding Status}" CellTemplateSelector="{DynamicResource StatusColoredDataTemplate}"/>

And then, I created the following class

using System.Windows;
using System.Windows.Controls;

namespace DomainExperience.Pane.DomainFile
public class StatusColoredDataTemplateClass : DataTemplateSelector
public override DataTemplate SelectTemplate(object item, DependencyObject container)
// Some logic here that I haven't defined yet...

The intention here is to change the color of the text that goes into the Status column depending on its content. I want to have Green text when the result is Passed and red text when it is Failed.

I've read that I should create a class that implements a DataTemplateSelector. However, I am not able to hit a breakpoint in this class whenever the Panel that is related to this XAML gets updated.

  1. What is wrong in my XAML logic?

  2. Am I missing something else maybe on my ViewModel logic?

  3. What sort of code do I need to implement in my class to change the color of the text?


UPDATE: The Results property is associated to the following class

public class ResourceStaticAnalysisResults
public string Name { get; set; }
public List<string> ErrorList { get; set; }
public string Status { get; set; }

Answer Source

A DataTemplateSelector is overkill because you don't need to change the DataTemplate itself, just a property of one of its controls. Instead, you can define a single, fixed DataTemplate for that column and manage the change of color with a style:

<DataTemplate x:Key="StatusColoredDataTemplate" DataType="{x:Type system:Boolean}">
    <TextBlock Text="{Binding}">
            <Style TargetType="{x:Type TextBlock}">
                <Setter Property="Foreground" Value="Green" />
                    <DataTrigger Binding="{Binding}" Value="False">
                        <Setter Property="Foreground" Value="Red" />

And the column:

    DisplayMemberBinding="{Binding Status}"
    CellTemplate="{StaticResource StatusColoredDataTemplate}" />
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download