有時候你是不是也會遇到要在wpf後台給某個控制項設定背景色或者給文字設定前景色彩的情況。
本人最近看到一個從自訂的combobox讀取系統字型和顏色的執行個體,該執行個體實現了隨字型combobox選項改變而改變字型的設定,而顏色combobox卻沒有實現,於是自己也想設定一下。結果發現顏色從前台好像不好設定成動態,於是嘗試從後台combobox_SelectionChanged事件設定。
要設定顏色,首先要擷取顏色。擷取顏色的方式我總結了五種:
1、 Color color = Color.FromArgb(透明度, red數字, green數字, blue數字); //這四個數字範圍都是(0-255) Color color = Color.FromRgb(red數字, green數字, blue數字);//預設透明度為255;2、Color color = (Color)ColorConverter.ConvertFromString(“Blue”);3、 if (e.Source is ComboBox) { var value = (e.Source as ComboBox).SelectedValue; int start = value.ToString().IndexOf("Color"); string selectcolor = value.ToString().Substring(start+5); Color color = (Color)ColorConverter.ConvertFromString(selectcolor); textblock.Foreground = new SolidColorBrush(color); }4、TBlock_content.Foreground = Brushes.Blue; (對於有Brushes的時候)
這裡我們著重說一下第三種,value擷取的值是:System.Windows.Media.Color 顏色名 (比如System.Windows.Media.Color Blue)。所以我們需要截取出後面的名字,然後使用(Color)ColorConverter.ConvertFromString(selectcolor) 轉換為顏色格式。注意,不能使用ColorConverter.ConvertFromString(selectcolor) as Color;提示錯誤Color必須為非Null值。
5 SolidColorBrush myBrush = new SolidColorBrush(System.Windows.Media.Color.FromArgb(0xFF, 0x25, 0x56, 0x87)); button.Background = (System.Windows.Media.Brush)myBrush;