【C#/WPF】Button按钮动态设置Background背景颜色

时间:2023-03-09 09:27:47
【C#/WPF】Button按钮动态设置Background背景颜色

学习笔记:

在XAML中给Button设置颜色大家都懂的,本篇只是记录用C#代码动态生成的按钮设置Background背景颜色。

【C#/WPF】Button按钮动态设置Background背景颜色

new一个Button,设置Background时可看到该属性类型是System.Window.Media.Brush Control.Background,如果直接Background = new Brush()会像上图那样报错,因为这个Bursh类是个抽象类。

解决办法:
在Button类上按F1,在MSDN中可以看到Button在XAML和C#中的用法。
【C#/WPF】Button按钮动态设置Background背景颜色

注意,直接写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://*.com/questions/4991041/c-sharp-change-a-buttons-background-color
设置背景为某张图片 http://*.com/questions/15892290/how-to-change-set-background-image-of-a-button-in-c-sharp-wpf-code