【C#/WPF】Button按鈕動態設置Background背景顏色


學習筆記:

在XAML中給Button設置顏色大家都懂的,本篇只是記錄用C#代碼動態生成的按鈕設置Background背景顏色。

這里寫圖片描述

new一個Button,設置Background時可看到該屬性類型是System.Window.Media.Brush Control.Background,如果直接Background = new Brush()會像上圖那樣報錯,因為這個Bursh類是個抽象類。

解決辦法:
在Button類上按F1,在MSDN中可以看到Button在XAML和C#中的用法。
這里寫圖片描述

注意,直接寫Brush指的是System.Drawing.Brush,而這里需要的是System.Windows.Media.Brushes。

Background = System.Windows.Media.Brushes.White

如果想給按鈕背景設置為一張圖片:

Button btn = new Button();
ImageBrush brush = new ImageBrush();
brush.ImageSource = new BitmapImage(new Uri("Images/test.png", UriKind.Relative));
btn.Background = brush;

重要參考:

設置背景為某種顏色 http://stackoverflow.com/questions/4991041/c-sharp-change-a-buttons-background-color
設置背景為某張圖片 http://stackoverflow.com/questions/15892290/how-to-change-set-background-image-of-a-button-in-c-sharp-wpf-code

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM