简体   繁体   English

基于单选按钮选择在运行时更改图像

[英]Change Image at Runtime Based On RadioButton Selection

I need to change the background image at runtime, based on which RadioButton the user clicks. 我需要在运行时根据用户单击哪个RadioButton更改背景图像。 I'm doing this in a WPF project in Visual Studio, and I need to put the code in the Checked event in the xaml.cs file 我正在Visual Studio的WPF项目中执行此操作,并且需要将代码放入xaml.cs文件中的Checked事件中

I have an Image control called imgBackground, with 6 images in its Source collection, which are listed in an Images folder in the Solution Explorer. 我有一个名为imgBackground的图像控件,其Source集合中有6张图像,这些图像列在Solution Explorer的Images文件夹中。

I've tried: 我试过了:

this.imgBackground.Source = "filename.jpg";

both with and without the quotes, and with various paths (I've tried too many different variations to list them all here) and nothing works - everything I've tried just gives an error in the editor, before I even try to build and run anything (the error given varies depending on what I'm trying at the time). 无论带引号,不带引号,以及各种路径(我尝试了太多不同的变体形式都无法在此处列出),并且没有任何效果-我尝试过的所有操作都在编辑器中出现错误,甚至没有尝试构建和运行任何命令(给出的错误取决于我当时的尝试)。

If you are using relative paths as filenames like 如果您使用相对路径作为文件名,例如

this.imgBackground.Source = "filename.jpg";

then these files must be in the same directory as the .exe of your program is. 那么这些文件必须与程序的.exe位于同一目录中。 One workaround would be to use absolute paths like 一种解决方法是使用绝对路径,例如

this.imgBackground.Source = @"C:\MyFolder\MyProject\filename.jpg";

Or, even further use the packaging mechanism of WPF or pack your images as resources into your assembly. 或者,甚至进一步使用WPF的打包机制,或将图像作为资源打包到程序集中。 Look at this thread. 这个线程。

EDIT: 编辑:

For your clarification: 为了您的澄清:

The Source -property demands an System.Windows.Media.ImageSource -object, which you must provide. Source属性需要一个System.Windows.Media.ImageSource ,您必须提供该对象。 Do it like this: 像这样做:

BitmapImage bi3 = new BitmapImage();
bi3.BeginInit();
bi3.UriSource = new Uri("filename.jpg", UriKind.Relative);
bi3.EndInit();
this.imgBackground.Source = bi3;

Please refer to this documentation here. 请在此处参考文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM