Search code examples
wpftextblock

Apply a property for a part of text of textblock in WPF


i want , when a part of text of textblock is 'Thomas' , around the text be blue.

How do i do this?


Solution

  • You need a converter:

    public class StringPropertyContainsThomasConverter : IValueConverter {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
            if(value != null) {
                if(value.ToString().Contains("Thomas")) return Brushes.Blue; //replace with whatever color you want
            }
            return Brushes.White;
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
            throw new NotImplementedException();
        }
    }
    

    Usage in XAML:

    <Window.Resources>
        <local:StringPropertyContainsThomasConverter x:Key="StringPropertyContainsThomasConverter"/>
    </Window.Resources>
    <TextBlock Background="{Binding RelativeSource={RelativeSource self},
                                    Path=Text,
                                    Converter={StaticResources StringPropertyContainsThomasConverter}}"/>