2011-12-30 72 views
0

我想让WPF应用程序的用户有机会更改应用程序的背景颜色。为此,他有一个组合框与一些值:WPF BackgroundColor

 cbSetBackground.Items.Add("green"); 
     cbSetBackground.Items.Add("red"); 
     cbSetBackground.Items.Add("blue"); 
     cbSetBackground.Items.Add("yellow"); 

现在,与点击事件,我必须将backgroundcolor到选定的颜色。我试过这样的

this.Background = Brushes. + cbSetBackground.SelectedItem.ToString(); 

当然,这不工作。 我该如何管理?

回答

0

你可以给这一个尝试:

BrushConverter bc = new BrushConverter(); 
this.Background= (Brush)bc.ConvertFrom(cbSetBackground.SelectedItem.ToString()); 

OR

BrushConverter bc = new BrushConverter(); 
this.Background= (Brush)bc.ConvertFromString(cbSetBackground.SelectedItem.ToString()); 

OR

Brush myBrush = new SolidBrush(Color.FromName(cbSetBackground.SelectedItem.ToString())); 
this.Background=myBrush; 

退房的BrushConverter类在这里http://msdn.microsoft.com/en-us/library/system.windows.media.brushconverter.convertfromstring.aspx

+0

非常感谢你。你知道吗,我可以如何设置这个背景颜色到我的整个应用程序?我必须在构造函数中提交它吗? – user896692 2011-12-30 15:34:30

1

您应该可以使用BrushConverter(http://msdn.microsoft.com/en-us/library/system.windows.media.brushconverter.aspx)。

BrushConverter conv = new BrushConverter(); 
SolidColorBrush brush = conv.ConvertFromString(cbSetBackground.SelectedItem.ToString()) as SolidColorBrush; 
this.Background = brush; 
0

这应该工作

string colorStr = cbSetBackground.SelectedItem.ToString(); 
Color c = (Color)TypeDescriptor.GetConverter(typeof(Color)).ConvertFromString(colorStr); 

this.Background = c; 

但是你可能需要的第一个字符改为大写。