如何以编程方式将C#中的Image Source设置为XAML Static Resource?

Dan*_*ett 8 c# wpf xaml staticresource

我有这样ResourceDictionaryMain.xaml:

<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>
Run Code Online (Sandbox Code Playgroud)

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

<Image Name="TypeIcon" HorizontalAlignment="Left" VerticalAlignment="Center"
    Source="{StaticResource Customer}" Height="16" Width="16"/>
Run Code Online (Sandbox Code Playgroud)

我试图改变TypeIconSource,从客户项目投资在C#方法.

我尝试过使用:

TypeIcon.Source = "{StaticResource Project}";
Run Code Online (Sandbox Code Playgroud)

但我得到这个错误:

无法隐式转换stringSystem.Windows.Media.ImageSource

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

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

Dan*_*ett 14

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

TypeIcon.Source = (ImageSource) Resources["Project"];
Run Code Online (Sandbox Code Playgroud)


Dev*_*per 10

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

即如何动态设置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;
Run Code Online (Sandbox Code Playgroud)

即如何动态设置应用程序的图标

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