您的位置:首页 > 编程语言 > C#

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

2017-01-18 09:27 681 查看
学习笔记:

在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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  wpf c#