WPF:将画笔恢复为默认/原始

时间:2009-08-20 14:15:33

标签: wpf user-controls default

我是WPF的新手。

目前我正在为名为“LabeledTextbox”的表单元素进行usercontrol,其中包含标签,文本框和错误消息的文本块。

当使用代码添加错误消息时,我想将文本框的边框设置为红色。但是,当错误消息被删除时,我想回到文本框的默认边框颜色。 我觉得必须有一个非常简单的方法来做到这一点。

我的代码:

(在公共部分类LabeledTextbox:UserControl中)

public string ErrorMessage
{
    set
    {
        if (string.IsNullOrEmpty(value))
        {
            _textbox.BorderBrush = Brushes.Black; //How do I revert to the original color in the most elegant way?
        }
        else
        {
            _textbox.BorderBrush = Brushes.Red;
        }

        _errorMessage.Text = value;
    }
}

5 个答案:

答案 0 :(得分:45)

您可以使用

_textBox.ClearValue(TextBox.BorderBrushProperty);

这将删除直接赋值,并返回样式或模板定义的值。

答案 1 :(得分:10)

您可以从 SystemColors

类中获取默认颜色

以下是所有系统颜色的列表: http://msdn.microsoft.com/de-de/library/system.windows.systemcolors.aspx

客户区的默认背景颜色

     _textbox.Background = SystemColors.WindowBrush;

客户区内的默认文字颜色

     _textbox.SystemColors.WindowTextBrush

答案 2 :(得分:3)

我可能会迟到,但对于未来的读者,您也可以使用Button.BackgroundProperty.DefaultMetadata.DefaultValue来达到此目的。当您使用转换器时,此功能非常有用,您需要返回值,因此无法使用ClearValue()来电。

答案 3 :(得分:0)

这有用吗?将其设置为黑色比使用ClearValue方法

更好
public string ErrorMessage
{
    set
    {
        if (string.IsNullOrEmpty(value))
        {
            _textbox.Background = Brushes.Black;
        }
        else
        {
            _textbox.Background = Brushes.Red;
        }

        _errorMessage.Text = value;
    }
}

答案 4 :(得分:0)

只需存储默认设置。这是一个代码示例。

        System.Windows.Media.Brush save;

        private void Window_Loaded(object sender, RoutedEventArgs e)
                {
          //Store the default background 
        save = testButton.Background;

        }


        private void ChangeBackground(){

        testButton.Background = Brushes.Red;

        }

        private void restoreDefaultBackground(){

        //Restore default Backgroundcolor

        testButton.Background = save;

        }
相关问题