30

我是 WPF 的新手。

目前我正在为名为“LabeledTextbox”的表单元素制作一个用户控件,其中包含一个标签、一个文本框和一个用于错误消息的文本块。

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

我的代码:

(在公共部分类 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;
    }
}
4

5 回答 5

50

你可以使用

_textBox.ClearValue(TextBox.BorderBrushProperty);

这将删除直接分配的值并返回到样式或模板定义的值。

于 2009-08-20T14:20:29.967 回答
15

您可以从SystemColors类中获取默认颜色

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

客户区的默认背景颜色:

     _textbox.Background = SystemColors.WindowBrush;

客户区内的默认文本颜色:

     _textbox.SystemColors.WindowTextBrush
于 2011-10-05T14:41:41.787 回答
4

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

于 2015-08-20T05:14:45.583 回答
0

这行得通吗?将其设置为黑色比使用 ClearValue 方法更好

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

        _errorMessage.Text = value;
    }
}
于 2009-08-20T14:24:59.117 回答
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;

        }
于 2011-05-30T12:08:14.553 回答