Search code examples
c#wpfxamldatatrigger

Datatrigger if string contains certain characters


im struggling with figuring out how to check if a string contains certain characters / words and make the datatriggers go off based on that.

In my example below I would like the datatrigger to go off when there is a color in the value, and what comes after doesnt matter. The first trigger, if value contains "RED" trigger should go off no matter if it says RED Apple ,RED car, RED little ball etc.

<DataTrigger Binding="{Binding Name}" Value="RED Apple" >
<Setter Property="Foreground" Value="Red" />
</DataTrigger>

<DataTrigger Binding="{Binding Name}" Value="YELLOW Lemon" >
<Setter Property="Foreground" Value="Yellow" />
</DataTrigger>

<DataTrigger Binding="{Binding Name}" Value="GREEN Pear" >
<Setter Property="Foreground" Value="Green" />
</DataTrigger>

How can I achieve this


Solution

  • Create a Converter

    public class ColorConverter : IValueConverter {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
            return ((string)value.Contains("Color");
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
            throw new NotImplementedException();
        }
    }
    

    Then use the following XAML.

    <Window.Resources>
        <myNamespace:ColorConverter x:Key="ColorConverter" Color="red" />
    </Window.Resources>
    
    <DataTemplate.Triggers>
        <DataTrigger Binding="{Binding Path=Color,
                                       Converter={StaticResource ColorConverter}}">
            <DataTrigger.Value>true</DataTrigger.Value>
            <Setter TargetName="Color" Property="Foreground" Value="Red"/> 
        </DataTrigger>
    </DataTemplate.Triggers>