Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/12.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# 在代码隐藏中使用资源映像_C#_Wpf_Visual Studio_Resources - Fatal编程技术网

C# 在代码隐藏中使用资源映像

C# 在代码隐藏中使用资源映像,c#,wpf,visual-studio,resources,C#,Wpf,Visual Studio,Resources,我需要动态地更改应用于我的一个按钮的背景图像,但不知道如何更改。图像将添加到项目中,并将其生成操作设置为“资源”。我尝试了以下方法: buttonUnits.Background = new ImageBrush(new BitmapImage(new Uri("/Images/InchDOWN.png",UriKind.Relative))); 这将成功编译,但将崩溃,DirectoryNotFoundException显示“找不到路径“C:\Images\inchund.png”的一部分。

我需要动态地更改应用于我的一个按钮的背景图像,但不知道如何更改。图像将添加到项目中,并将其生成操作设置为“资源”。我尝试了以下方法:

buttonUnits.Background = new ImageBrush(new BitmapImage(new Uri("/Images/InchDOWN.png",UriKind.Relative)));
这将成功编译,但将崩溃,DirectoryNotFoundException显示“找不到路径“C:\Images\inchund.png”的一部分。”


我不希望应用程序在磁盘上查找图像。如何将图像用作嵌入式资源?我认为这涉及到将构建操作更改为嵌入式资源,但如何在代码隐藏中使用此资源?

您必须将映像构建为资源而不是嵌入式资源。资源是专门供WPF项目使用的

要在程序代码中使用它,请执行以下操作:

 buttonUnits.Background = new ImageBrush(new BitmapImage(new Uri("pack://application:,,,/Images/InchDOWN.png")));
这在我推荐的XAML中要容易得多

编辑

我忘记了图片前的正斜杠,这可能是问题所在。如果您需要更多信息,请点击这里


也许你应该发布一个问题,说明你到底想完成什么,并希望找到解决多状态按钮问题的不同方法。

我已经尝试过了,但我得到了一个NotSupportedException,它说“URI前缀无法识别”。我同意,在XAML中设置图像会更容易,但我的目标是一种多状态按钮,不知道如何在XAML中实现。