Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/319.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# WPF无法将system.drawing.bitmap隐式转换为media.brush_C#_Wpf_Xaml - Fatal编程技术网

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

C# WPF无法将system.drawing.bitmap隐式转换为media.brush,c#,wpf,xaml,C#,Wpf,Xaml,我想在我的WPF应用程序中手动更改按钮的背景 我已将图像导入到我的资源中,我希望执行以下操作: MyButton.Background = MyProject.Properties.Resources.myImage; 但我得到了一个错误: 无法将system.drawing.bitmap隐式转换为media.brush 我该怎么做???您应该先阅读有关画笔的内容 然后使用ImageBrush,如下所示: MyButton.Background = new ImageBrush(...);

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

我已将图像导入到我的资源中,我希望执行以下操作:

MyButton.Background = MyProject.Properties.Resources.myImage;
但我得到了一个错误:

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


我该怎么做???

您应该先阅读有关画笔的内容

然后使用ImageBrush,如下所示:

MyButton.Background = new ImageBrush(...);
或者,也许,把刷子放在资源上

更新

您可以轻松找到如何从位图创建imageSource。例如比如:


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

与其他文件一样,您可以直接将图像文件添加到VisualStudio项目中。如果有多个图像,将它们放在项目的子文件夹(例如称为图像)中可能是有意义的。该文件的生成操作必须设置为Resource,这是图像文件的默认值

现在,您可以从创建位图图像到该文件

最后,从BitmapImage创建ImageBrush以设置背景属性

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

背景是错误的属性,你需要像BackgroundImage@CSharpie你错了,背景是正确的属性。你需要将它设置为图像笔刷。哦,好的。今天学到了一些新东西:这不起作用,因为myImage的类型是System.Drawing.Bitmap。我添加了一种将位图转换为源代码的方法
var uri = new Uri("pack://application:,,,/images/myImage.jpg");
var image = new BitmapImage(uri);
MyButton.Background = new ImageBrush(image);