2009-08-20 67 views
27

我是WPF的一名完整新手。WPF:恢复笔刷为默认/原创

目前我正在为名为“LabeledTextbox”的表单元素进行一个用户控件,该表单包含一个标签,一个文本框和一个用于errormessages的文本块。

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

我的代码:

(公共部分类LabeledTextbox:用户控件)

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

回答

43

你可以使用

_textBox.ClearValue(TextBox.BorderBrushProperty); 

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

+1

太好了,谢谢! *将dependencyproperty研究添加到待办事项列表* – 2009-08-20 14:25:30

+0

非常感谢,非常有用的文章。我尝试使用brush.clone方法存储默认的笔刷,但是根据.net,系统默认不存在笔刷。谢谢! – JustinKaz 2010-05-27 16:34:33

+2

这对我不起作用。当我想要引起注意时,我将背景设置为海蓝宝石。我尝试使用ClearValue将其还原回来,但仍保持为海蓝宝石。看看这篇文章:(http://wpf.2000things.com/tag/clearvalue/)告诉我,ClearValue将它恢复到最后指定的值。所以我试着将背景属性设置为Nothing,它工作。标签背景现在是默认颜色。 – tolsen64 2015-04-09 17:27:04

0

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

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

     _errorMessage.Text = value; 
    } 
} 
+0

哦,对不起,我在我的文章中犯了一个错误。它并不是因为默认是渐变颜色。 – 2009-08-20 14:37:53

+0

@托马斯股票:0从未测试过它。所以也很抱歉。 – 2009-08-20 14:39:23

0

只存储默认设置。这里有一个代码excample。

 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; 

     } 
9

您可以从类抢默认颜色systemColors中

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

默认客户区域的背景颜色

 _textbox.Background = SystemColors.WindowBrush; 

默认客户端区域内文本颜色

 _textbox.SystemColors.WindowTextBrush 
+1

这个答案在MVVM环境中很有用。在那里,我无法清除BorderBrushProperty,就像Daniel在其他方面很好的答案一样。但是通过在视图模型的属性中显式地返回刷子来将控件的背景设置为其默认画笔作品。 – Julian 2016-07-25 15:44:29

3

我可能会迟到了,但对于未来的读者,你也可以使用Button.BackgroundProperty.DefaultMetadata.DefaultValue用于此目的。当你使用转换器时,这是特别有用的,你需要返回一个值,因此不能使用ClearValue()调用。