wpf图像资源和在运行时在wpf控件中更改图像 [英] wpf image resources and changing image in wpf control at runtime

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

问题描述

我想知道如何在C#代码中动态使用字典资源 - ie ..我想在运行时从字典中的图像资源加载图像



我有一个程序,在WPF字典中有3个图像 - 这些图像设置为图像资源。



然后在我的WPF窗口中的代码我想根据用户发起的事件加载三个图像中的任何一个。



没有真正的代码,我没有显示任何我已经完成的工作。



想法? / p>

解决方案

首先,确保您已经定义了这样的图像资源:



pre $ < 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文件中,确保你有这样的东西:

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

现在,在代码隐藏中,您可以使用FindResource()方法来查找图像资源通过它的关键名称(资源字典中ImageSource上的x:Key属性的值)如下所示:

  imageControl。 Source =(ImageSource)FindResource(image1); 

希望这有帮助!


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

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.

Ideas?

解决方案

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>

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>

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天全站免登陆