簡體   English   中英

在 WPF 中使用 WinForms ColorDialog 出現錯誤:“顏色”參數類型對於格式化屬性“背景”無效

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

此問題已在網上得到解答,我正在嘗試按照這些答案進行操作,但仍然出現以下錯誤。 問題:我在這里可能做錯了什么,我們該如何解決?

筆記:

  1. 我正在使用Windows Form ColorDialog 類來實現wpf的類似功能
  2. 我不想使用第三方工具(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 類(我在同一個項目中創建):

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

錯誤

“顏色”參數類型對格式屬性“背景”無效

Background屬性的類型是Brush ,而不是Color

您需要創建一個SolidColorBrush

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM