2009-06-02 83 views
10

我想知道如何动态地使用字典资源在后面的C#代码 - 即..我想在运行时从图像资源词典wpf图像资源和运行时在wpf控制中更改图像

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

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

有没有真正的代码,我必须显示,因为我没有做的工作。

想法?

回答

20

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

<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"); 

希望这有助于!

+0

啊,我错过的是我的字典合并到Window.Resources - 非常感谢! – Tab 2009-06-03 15:27:34

1

这是一个除了the accepted answer: 当ViewModel内MVVM工作,确保从出增加了资源目录视图中使用FindResource

<Window x:Class="My.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:ViewModels="clr-namespace:My.ViewModels" 
     Title="USA Hockey Player Evaluation tool" 
     Icon="/USAHockeyPlayerEval;component/View/Images/HET.ico" 
     SizeToContent="WidthAndHeight" 
     MinHeight="500px" MinWidth="800px"> 
    <Window.Resources> 
     <ResourceDictionary> 
      <ResourceDictionary.MergedDictionaries> 
       <ResourceDictionary Source="Images.xaml" /> 
      </ResourceDictionary.MergedDictionaries> 
     </ResourceDictionary> 
    </Window.Resources> 
    <Window.DataContext> 
     <ViewModels:MainWindowMV/> 
    </Window.DataContext> 
    <StackPanel> 
     <Menu> 
      <MenuItem Header="File"> 
       <MenuItem Header="Save"></MenuItem> 

我在这种情况下,视图是一个窗口(我不知道正确的MVVM ;-))

Image img = new Image();          
img.Source = (ImageSource)WindowReference.FindResource("Pluse"); 

这里WindowReferenceMy.MainWindow参考。