我想在我的WPF应用程序中手动更改按钮的背景.
我有一个图像导入我的资源,我想这样做:
MyButton.Background = MyProject.Properties.Resources.myImage;
Run Code Online (Sandbox Code Playgroud)
但我得到错误:
无法将system.drawing.bitmap隐式转换为media.brush
我怎样才能做到这一点??
你应该先在这里阅读一下刷子.
然后使用ImageBrush,像这样:
MyButton.Background = new ImageBrush(...);
Run Code Online (Sandbox Code Playgroud)
(或者,也许,将刷子放入资源......)
UPDATE
您可以找到如何从位图easilly创建imageSource.例如,这里.喜欢:
var bitmapSource = Imaging.CreateBitmapSourceFromHBitmap(MyProject.Properties.Resources.myImage.GetHbitmap(),
IntPtr.Zero,
Int32Rect.Empty,
BitmapSizeOptions.FromEmptyOptions());
MyButton.Background = new ImageBrush(bitmapSource);
Run Code Online (Sandbox Code Playgroud)
在WPF应用程序中,您通常不会像在WinForms中那样添加图像资源.
而是将图像文件直接添加到Visual Studio项目中,就像任何其他文件一样.如果有多个图像,将它们放在项目的子文件夹中可能是有意义的(例如,称为"图像").该Build Action文件必须设置为Resource(这是图像文件的默认值).
现在,您可以BitmapImage从包URI创建该文件.
最后创建一个ImageBrush从BitmapImage设置的Background属性.
var uri = new Uri("pack://application:,,,/images/myImage.jpg");
var image = new BitmapImage(uri);
MyButton.Background = new ImageBrush(image);
Run Code Online (Sandbox Code Playgroud)