WPF 无法将 system.drawing.bitmap 隐式转换为 media.brush

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20600666/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 10:13:14  来源:igfitidea点击:

WPF cannot implicitly convert system.drawing.bitmap to media.brush

c#wpfxaml

提问by Harry Boy

I want to change the background of a button manually in my WPF app.

我想在我的 WPF 应用程序中手动更改按钮的背景。

I have an image imported into my resources and I want to do:

我有一个图像导入到我的资源中,我想做:

MyButton.Background = MyProject.Properties.Resources.myImage;

But I get the error:

但我收到错误:

cannot implicitly convert system.drawing.bitmap to media.brush

无法将 system.drawing.bitmap 隐式转换为 media.brush

How can I do this??

我怎样才能做到这一点??

回答by JleruOHeP

You should read about brushes first here.

您应该首先在此处阅读有关画笔的信息

And then use ImageBrush, something like this:

然后使用ImageBrush,像这样:

MyButton.Background = new ImageBrush(...);

(or, maybe, put the brush into resources...)

(或者,也许,将画笔放入资源中......)

UPDATE

更新

You can find how to create imageSource from bitmap easilly. for example, here. Like:

您可以找到如何从位图轻松创建 imageSource。例如,这里。喜欢:

var bitmapSource = Imaging.CreateBitmapSourceFromHBitmap(MyProject.Properties.Resources.myImage.GetHbitmap(),
                                  IntPtr.Zero,
                                  Int32Rect.Empty,
                                  BitmapSizeOptions.FromEmptyOptions());
MyButton.Background = new ImageBrush(bitmapSource);

回答by Clemens

In a WPF application, you do usually not add image resources as you did in WinForms.

在 WPF 应用程序中,您通常不会像在 WinForms 中那样添加图像资源。

Instead you add the image file directly to your Visual Studio project, just like any other file. If there are multiple images, it may make sense to put them in a subfolder of the project (e.g. called "images"). The Build Actionof that file has to be set to Resource(which is the default for image files).

而是将图像文件直接添加到 Visual Studio 项目,就像任何其他文件一样。如果有多个图像,将它们放在项目的子文件夹中可能是有意义的(例如,称为“图像”)。该Build Action文件的 必须设置为Resource(这是图像文件的默认值)。

Now you can create a BitmapImagefrom a Pack URIto that file.

现在您可以BitmapImagePack URI创建到该文件。

Finally you create an ImageBrushfrom the BitmapImageto set the Backgroundproperty.

最后,您ImageBrush从 中创建一个BitmapImage来设置Background属性。

var uri = new Uri("pack://application:,,,/images/myImage.jpg");
var image = new BitmapImage(uri);
MyButton.Background = new ImageBrush(image);