【问题标题】:How to set Image Source in C# to XAML Static Resource programmatically?如何以编程方式将 C# 中的图像源设置为 XAML 静态资源?
【发布时间】:2013-09-04 22:52:28
【问题描述】:

我在Main.xaml 中有这个ResourceDictionary

<Window.Resources>
    <ResourceDictionary>
        <BitmapImage x:Key="Customer" UriSource="Icons/customer.png"/>
        <BitmapImage x:Key="Project" UriSource="Icons/project.png"/>
        <BitmapImage x:Key="Task" UriSource="Icons/task.png"/>
    </ResourceDictionary>
</Window.Resources>

我最初使用以下方法设置图像:

<Image Name="TypeIcon" HorizontalAlignment="Left" VerticalAlignment="Center"
    Source="{StaticResource Customer}" Height="16" Width="16"/>

我正在尝试在 C# 方法中将 TypeIconSourceCustomer 更改为 Project

我尝试过使用:

TypeIcon.Source = "{StaticResource Project}";

但我收到此错误:

无法将类型 string 隐式转换为 System.Windows.Media.ImageSource

我尝试使用new ImageSource() 定义图像,但这也不起作用。

如何在 C# 中以编程方式更改图像的 Source

【问题讨论】:

    标签: c# wpf xaml staticresource


    【解决方案1】:

    经过大量谷歌搜索,在写这个问题时,我想出了如何去做:

    TypeIcon.Source = (ImageSource) Resources["Project"];
    

    【讨论】:

    • 这里是什么?对于“ImageSource”,您还需要包括“使用 System.Windows.Media;”。但是“资源”在当前上下文中仍然不可用...
    【解决方案2】:

    它不适用于静态资源,但无论如何可能会有用... :)

    即如何动态设置 Grid 的背景

    var myBrush = new ImageBrush();
                var image = new Image
                                {
                                    Source = new BitmapImage(
                                        new Uri(
                                            "pack://application:,,,/YourAppName;component/Images/Boo.png"))
                                };
    myBrush.ImageSource = image.Source;
    MainGrid.Background = myBrush;
    

    即如何动态设置应用图标

    var idleIco = new Image
                {
                    Source = new BitmapImage(
                        new Uri(
                            "pack://application:,,,/YourAppName;component/Images/idle.ico"))
                };
    SomeObjectYouAreUsingToSet.IconSource =idleIco.Source;
    

    【讨论】:

      【解决方案3】:

      你可以使用ImageSourceConverter类来获取你想要的,例如:

      img1.Source = (ImageSource)new ImageSourceConverter().ConvertFromString("/Assets/check.png");
      

      【讨论】:

      • Media 命名空间不适用于通用应用程序System.Windows.Media.ImageSourceConverter
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-24
      • 2010-12-20
      • 2015-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多