简体   繁体   English

在 WPF 中使用 WinForms ColorDialog 出现错误:“颜色”参数类型对于格式化属性“背景”无效

[英]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我正在使用Windows Form ColorDialog 类来实现wpf的类似功能
  2. I do not want to use a third party tool (WPFToolKit etc).我不想使用第三方工具(WPFToolKit 等)。

WPF Relevant Code : 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 (I created in the same project): ColorHelper 类(我在同一个项目中创建):

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' “颜色”参数类型对格式属性“背景”无效

The Background property is of type Brush , not Color . Background属性的类型是Brush ,而不是Color

You need to create a SolidColorBrush .您需要创建一个SolidColorBrush

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM