WPF BackgroundColor



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

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

现在,使用Click-Event,我必须将背景色设置为所选颜色。我试过了

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

当然,这是行不通的。我该怎么做呢?

你应该能够使用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;

你可以试试这个:

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

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

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

应该可以了

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

但是您可能需要将第一个字符更改为大写

最新更新