Search code examples
c#wpfxamldata-bindingconverters

Binding Converter how to pass a parameter to function


In my window.xaml I have the following code:

 xmlns:converters="clr-namespace:HMIPlc.Helpers"

 <Window.Resources>
    <ResourceDictionary>
        <converters:ColorConverter x:Key="ColorOnChange"/>
    </ResourceDictionary>
</Window.Resources>

<Rectangle Fill="{Binding Path=varUnit.InSimulation, Converter={StaticResource ColorOnChange}}"/> 

I want to give also a value in a string "Yellow" or "Orange" to the function, so I can use the same function for different rectangles with different colors.

My ColorConverter.cs class inside the Helpers directory:

public class ColorConverter : IValueConverter
{
    public ColorConverter()
    {
    }

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        bool tempBool = (bool)value;
        if(tempBool == true)
        {
            return new SolidColorBrush(Colors.Orange);
        } else
        {
            return new SolidColorBrush(Colors.White);
        }
    }

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

So that I can determine in my XAML if the color has to be orange or yellow. Is there any good method to do this?


Solution

  • You could set the CommandParameter property to a Brush or Color and cast the "parameter" argument in your converter:

    public class ColorConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            Color color = (Color)parameter;
            bool tempBool = (bool)value;
            if (tempBool == true)
            {
                return new SolidColorBrush(color);
            }
            else
            {
                return new SolidColorBrush(color);
            }
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
    

    XAML:

    <Rectangle Fill="{Binding Path=varUnit.InSimulation, Converter={StaticResource ColorOnChange},
            ConverterParameter={x:Static Colors.Orange}}"/>