2011-12-30 75 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; 

但是你可能需要的第一個字符改爲大寫。