WPF 无法将 system.drawing.bitmap 隐式转换为 media.brush
问题描述:
我想在我的 WPF 应用程序中手动更改按钮的背景.
I want to change the background of a button manually in my WPF app.
我有一张图片导入到我的资源中,我想做:
I have an image imported into my resources and I want to do:
MyButton.Background = MyProject.Properties.Resources.myImage;
但我收到错误:
无法将 system.drawing.bitmap 隐式转换为 media.brush
cannot implicitly convert system.drawing.bitmap to media.brush
我该怎么做??
答
您应该先阅读有关画笔的信息 这里.
You should read about brushes first here.
然后使用ImageBrush
,像这样:
MyButton.Background = new ImageBrush(...);
(或者,也许,将画笔放入资源中...)
(or, maybe, put the brush into resources...)
更新
您可以找到如何从位图轻松创建图像源.例如,此处.喜欢:
You can find how to create imageSource from bitmap easilly. for example, here. Like:
var bitmapSource = Imaging.CreateBitmapSourceFromHBitmap(MyProject.Properties.Resources.myImage.GetHbitmap(),
IntPtr.Zero,
Int32Rect.Empty,
BitmapSizeOptions.FromEmptyOptions());
MyButton.Background = new ImageBrush(bitmapSource);