简体   繁体   中英

WPF BackgroundColor

I want to give the user of my WPF-application the chance to change the backgroundcolor of the application. For that, he has a combobox with some values:

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

Now, with the Click-Event, I have to put the backgroundcolor to the selected color. I tried it like this

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

For sure, this isn´t working. How can I manage this?

You should be able to use the 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;

You can give this one a try:

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;

Check out the BrushConverter class here http://msdn.microsoft.com/en-us/library/system.windows.media.brushconverter.convertfromstring.aspx

This should work

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

this.Background = c;

But you might need to change the first character to uppercase.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM