WPF图像资源,在运行时的WPF控件改变形象 [英] wpf image resources and changing image in wpf control at runtime

查看:103
本文介绍了WPF图像资源,在运行时的WPF控件改变形象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何动态地在C#代码中使用词典资源的背后 - 即..我想一个字典

I would like to know exactly how to dynamically use a Dictionary Resource in the C# code behind - ie.. I would like to load images at runtime from an image resource within a dictionary

我有了一个WPF词典3图像的程序 - 这些都是设定为图像资源的图像在我的WPF窗口后面的代码

I have a program that has 3 images in a WPF Dictionary - these are images set as image resources.

然后我要加载基于用户发起的事件的三个​​图像中的任何一个。

Then in the code behind of my WPF Window I want to load any one of the three images based on user initiated events.

有没有真正的代码,我必须表明如无物,我已经做了工作。

There is no real code I have to show as nothing that I have done works.

想法?

推荐答案

首先,确保你定义了你的形象资源,像这样的:

First, make sure you've defined your image resources like this:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <ImageSource x:Key="image1">images/image1.jpg</ImageSource>
    <ImageSource x:Key="image2">images/image2.jpg</ImageSource>
</ResourceDictionary>



其次,我假设你的WPF词典有自己的文件。现在,你必须确保你已经合并了你的字典到你的主窗口的XAML(跳过这一步,如果你的资源字典窗口的XAML里面定义)。在窗口的XAML文件,请确保您有这样的事情:

Secondly, I'm assuming that your WPF dictionary is in its own file. Now you have to make sure you've merged your dictionary into your main window's XAML (skip this step if your resource dictionary is defined inside of the window's XAML). In your window's XAML file, make sure you have something like this:

<Window.Resources>
	<ResourceDictionary>
		<ResourceDictionary.MergedDictionaries>
			<ResourceDictionary Source="myDictionary.xaml" />
		</ResourceDictionary.MergedDictionaries>
	</ResourceDictionary>
</Window.Resources>

现在,在您的代码隐藏,你可以使用FindResource()方法来定位你的图像资源通过它的键名(x的值:在资源字典的ImageSource的关键属性),像这样:

Now, in your code-behind, you can use the FindResource() method to locate your image resource by it's key name (the value of the x:Key attribute on the ImageSource in the resource dictionary) like so:

imageControl.Source = (ImageSource)FindResource("image1");



希望这有助于!

Hope this helps!

这篇关于WPF图像资源,在运行时的WPF控件改变形象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆