【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