學習筆記:
在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