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

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

此问题已在线回答,我正在尝试按照这些回答进行操作,但仍然出现以下错误。 问题:我这里可能做错了什么,我们该如何解决?

注意:

  1. 我正在使用 Windows Form 中的 ColorDialog Class 来实现 wpf
  2. 中的类似功能
  3. 我不想使用第三方工具(WPFToolKit 等)。

WPF相关代码:

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(我在同一个项目中创建的):

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);
    }
}

错误:

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

Background propertyBrush 类型,而不是 Color

您需要创建一个 SolidColorBrush