wpf後台設定顏色(背景色,前景色彩)

來源:互聯網
上載者:User

有時候你是不是也會遇到要在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;

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.