Search code examples
c#wpfcolordialog

Using WinForms ColorDialog in WPF is giving error: 'Color' parameter type is not valid for formatting property 'Background'


This question has been answered online and I'm trying to follow those answers, but I'm still getting the following error. Question: What I may be doing wrong here and how can we resolve it?

NOTE:

  1. I'm using ColorDialog Class from Windows Form to implement the similar functionality in wpf
  2. I do not want to use a third party tool (WPFToolKit etc).

WPF Relevant Code:

Using ....
using System.Windows.Forms; //for winforms' ColorDialog
......
private void BtnTest_Click(object sender, RoutedEventArgs e)
{
   ColorDialog MyDialog = new ColorDialog(); //from Winform
   MyDialog.AllowFullOpen = false;
   MyDialog.ShowHelp = true;

if (MyDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
    try
    {
        TextSelection textSelection = mainRTB.Selection;
        if (!textSelection.IsEmpty)
        {
             //Use the WPF System.Windows.Media.Brushes class instead of System.Drawing.Brushes from WinForms:
            textSelection.ApplyPropertyValue(TextElement.BackgroundProperty, ColorHelper.ToSWMColor(MyDialog.Color)); //error occurs at this line
        }
    }
    catch (Exception ex)
    {
        System.Diagnostics.Debug.WriteLine(ex.Message);
    }
}
}

ColorHelper Class (I created in the same project):

using SDColor = System.Drawing.Color;
using SWMColor = System.Windows.Media.Color;

namespace ColorDialog_for_WPF
{
    public static class ColorHelper
    {
        public static SWMColor ToSWMColor(this SDColor color) => SWMColor.FromArgb(color.A, color.R, color.G, color.B);
        public static SDColor ToSDColor(this SWMColor color) => SDColor.FromArgb(color.A, color.R, color.G, color.B);
    }
}

Error:

'Color' parameter type is not valid for formatting property 'Background'


Solution

  • The Background property is of type Brush, not Color.

    You need to create a SolidColorBrush.