【问题标题】:wpf image resources and changing image in wpf control at runtimewpf 图像资源和在运行时在 wpf 控件中更改图像
【发布时间】:2010-10-30 17:57:07
【问题描述】:

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

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

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

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

想法?

【问题讨论】:

    标签: c# wpf image dictionary resources


    【解决方案1】:

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

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

    希望这会有所帮助!

    【讨论】:

    • 啊,我缺少的是将我的字典合并到 Window.Resources - 非常感谢!
    • 写得很好的回复。 +1,谢谢!对于这种情况,浏览 MSDN 很痛苦
    • 荣誉 - 简短而准确
    【解决方案2】:

    这是对the accepted answer 的补充: 在 MVVM 的 ViewModel 中工作时,请确保在添加资源目录的视图中使用 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"); 
    

    这里的WindowReference 是对My.MainWindow 的引用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-28
      • 1970-01-01
      • 2012-04-04
      • 2017-02-07
      • 2011-05-03
      • 1970-01-01
      • 2013-11-28
      • 2015-05-30
      相关资源
      最近更新 更多