guxin

学习笔记:

在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

 

分类:

技术点:

相关文章:

  • 2022-12-23
  • 2021-07-01
  • 2021-09-21
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-19
  • 2021-11-29
猜你喜欢
  • 2021-07-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-02-18
  • 2021-07-07
相关资源
相似解决方案