1

I have a list :

Name Age Description

which I need to display in a grid.

How to display the binded property of Description to grid where if a description contain a specific keyword as "Good","Kind" then it must be highlighted in such a way that for "Good" it must be pink and for "Kind" it must be in Red .

Example

Name Age Description

ABC 25 I am very Good person

XYZ 28 I am very Kind person

PQR 26 I am a jovial kind of person.

I need to use this MVVM

Model:

 private string name    
 public string Name { get { return name } set { name    = value; } }

 private int age
 public int Age{ get { return age}    set { age= value; }   }

 private string description
 public string Description{ get { return description} set { description= value; } }

In Xaml :-

<TextBlock  Name="tbDescription"   Text="{Binding RowData.Row.Description, Mode=OneWay}"
                                        Width="300" VerticalAlignment="Center" HorizontalAlignment="Left" TextTrimming="CharacterEllipsis" MinWidth="300">
TechBrkTru
  • 346
  • 1
  • 25
  • I want only the "Good" keyword forecolor in Pink and the rest part of Description in Black – TechBrkTru Dec 22 '17 at 07:28
  • see https://stackoverflow.com/questions/5535619/wpf-textblock-color-for-each-character and then https://stackoverflow.com/questions/1959856/data-binding-the-textblock-inlines – ASh Dec 22 '17 at 07:54

1 Answers1

2

You could use a ValueConverter to return the color you need based on the string.

public class ForeGroundColorConverter: IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, 
            System.Globalization.CultureInfo culture)
    {
        var color = (string)value;

        if(color.IndexOf("good", StringComparison.OrdinalIgnoreCase) >= 0)
        {
            // return 'Good' color.
        }
        else if (color.IndexOf("kind", StringComparison.OrdinalIgnoreCase) >= 0)
        {
            // return 'Kind' color.
        }
        // More cases.
    }

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

Then use this converter in your binding. (Apply to the control you need. I use TextBlock as an example.)

<TextBlock Name="Your text." 
           ForeGround={Binding Description, Converter={StaticResource ForeGroundColorConverter}/>

First add it to your XML namespaces:

xmlns:converters="clr-namespace:<YourNameSpace>"

You will need to add a resource to your window/control as well.

<Window.Resources>
    <converters.ForeGroundColorConverter x:Key="ForeGroundColorConverter"/>
</Window.Resources>
burnttoast11
  • 1,164
  • 16
  • 33