如何获取文本框的前景色和背景色,以便在颜色选择器中进一步使用



前景和背景属性属于Brush类型。如何获取颜色以便在颜色选择器中进一步使用?

我将前景和背景传递给属性窗口的c-tor,如下所示:

private void Menu_Properties_OnClick(object sender, RoutedEventArgs e)
{
    PropertiesDialog propDialog = new PropertiesDialog(TbTimer.Foreground, TimerPanel.Background);
    if (propDialog.ShowDialog() == true)
    {
        //set color to TbTimer textbox and TimerPanel WrapPanel
    }
}

TbTimer是TextBox,TimerPanel是WrapPanel。

这是属性窗口c-tor:

public PropertiesDialog(Brush foreground, Brush background)
{
    InitializeComponent();
    FontColorPicker.SelectedColor = foreground; //Compilation error
    BgColorPicker.SelectedColor = background; //Compilation error
}

给我Cannot implicitly convert type 'System.Windows.Media.Brush' to 'System.Windows.Media.Color'

如何获得画笔的颜色?

当您将XAML中元素的Background属性设置为类似"Red"的属性时,类型转换器会将字符串"Red"转换为SolidColorBrush对象,该对象的Color属性设置为适当的颜色。

所以这个:

<TextBlock Background="Red" />

相当于:

<TextBlock>
    <TextBlock.Background>
        <SolidColorBrush Color="Red" />
    </TextBlock.Background>
</TextBlock>

SolidColorBrush是唯一具有单一"颜色"的笔刷类型。其他画笔类型可能有不止一种颜色,或者可能根本不代表"颜色"(例如DrawingBrushVisualBrush)。

如果您希望对话框的构造函数将Brush对象作为参数,但又希望将它们作为单色处理,则需要根据@BenjaminPaul的回答将它们强制转换为SolidColorBrush对象。当然,笔刷的类型实际上可能不同,所以显式强制转换会失败,并出现异常。

你能做的最好的事情是这样的:

public PropertiesDialog(Brush foreground, Brush background)
{
    InitializeComponent();
    var solidForeground = foreground as SolidColorBrush;
    var solidBackground = background as SolidColorBrush;
    if (solidForeground == null || solidBackground == null)
    {
        // One or both of the brushes does not have a
        // single solid colour; what you do here is up to you
        throw new InvalidOperationException();
    }
    FontColorPicker.SelectedColor = solidForeground.Color;
    BgColorPicker.SelectedColor = solidBackground.Color;
}

只需更改您的方法签名:

public PropertiesDialog(System.Windows.Media.Color foreground, System.Windows.Media.Color background)
{
    InitializeComponent();
    FontColorPicker.SelectedColor = foreground; 
    BgColorPicker.SelectedColor = background; 
}
SelectedColour需要System.Windows.Media.Color类型,但您正试图分配画笔。。。试着按如下方式铸造。
public PropertiesDialog(Brush foreground, Brush background)
{
    InitializeComponent();
    FontColorPicker.SelectedColor = ((SolidColorBrush)foreground).Color;
    BgColorPicker.SelectedColor = ((SolidColorBrush)background).Color; 
}

最新更新