-1

I am trying to bind a foreground color to a WPF Textblock.

The property in the view model is a color, as directed by MvvmCross documentation:

private System.Drawing.Color _setValueColor;

        public System.Drawing.Color SetValueColor
        {
            get { return _setValueColor == null ? System.Drawing.Color.Green : _setValueColor; }
            set { SetProperty(ref _setValueColor, value); }
        }

The xaml text block is

    <TextBlock Grid.Column="3" Grid.Row="1" Margin="20"
           Text="{Binding SetMessage}" Foreground="{Binding SetValueColor, Converter={StaticResource NativeColor}}">
    </TextBlock>

I have a resources dictionary resource.xaml file which references the plug in. The plug-in is installed as a nu-get MvvmCross.Plugin.Color 7.1.2

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:color="clr-namespace:MvvmCross.Plugin.Color;assembly=MvvmCross.Plugin.Color" 
    <color:MvxNativeColorValueConverter x:Key="NativeColor"  />
</ResourceDictionary>

On the view I add the resource in the constructor

public SimpleReadWriteView()
        {
            var resourceDict = new System.Windows.ResourceDictionary();
            resourceDict.Source = new Uri("Resource.xaml", UriKind.Relative);
            Resources.MergedDictionaries.Add(resourceDict);
            InitializeComponent();
        }

When it's run, it throws a cast error:

InvalidCastException: Unable to cast object of type 'MvvmCross.Plugin.Color.MvxnativeColorValueConverter' to type 'System.Windows.Data.IValueConverter'.

I also tried to create my own converter by inheriting from MvxValueConverter and I get the same type of cast error, the converter cannot be cast to type System.Windows.Data.IValueConverter.

1 Answers1

1

Do not use System.Drawing.Color in a WPF application, it is a WinForms type. Use System.Windows.Media.Color instead:

private System.Windows.Media.Color setValueColor = System.Windows.Media.Colors.Green;

public System.Windows.Media.Color SetValueColor
{
    get { return setValueColor; }
    set { SetProperty(ref setValueColor, value); }
}

You do not need a Binding Converter. You may instead directly bind the Color property of a SolidColorBrush:

<TextBlock ... >
    <TextBlock.Foreground>
        <SolidColorBrush Color="{Binding SetValueColor}" />
    </TextBlock.Foreground>
</TextBlock>

Besides that, a converter from Color to Brush would look like this:

public class ColorToBrushConverter : IValueConverter
{
    public object Convert(
        object value, Type targetType, object parameter, CultureInfo culture)
    {
        return new SolidColorBrush((Color)value);
    }

    public object ConvertBack(
        object value, Type targetType, object parameter, CultureInfo culture)
    {
        return ((SolidColorBrush)value).Color;
    }
}
Clemens
  • 123,504
  • 12
  • 155
  • 268