如何以编程方式将C#中的图像源设置为XAML静态资源?
我在如何以编程方式将C#中的图像源设置为XAML静态资源?,c#,wpf,xaml,staticresource,C#,Wpf,Xaml,Staticresource,我在Main.xaml中有这个ResourceDictionary: <Window.Resources> <ResourceDictionary> <BitmapImage x:Key="Customer" UriSource="Icons/customer.png"/> <BitmapImage x:Key="Project" UriSource="Icons/project.png"/>
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>
但我得到了这个错误:
无法将类型string
隐式转换为System.Windows.Media.ImageSource
我曾尝试使用新ImageSource()
定义图像,但这也不起作用
如何用C#编程更改图像的
源代码
?在谷歌搜索了很多次之后,在写这个问题时,我想出了如何做:
TypeIcon.Source = (ImageSource) Resources["Project"];
您可以使用
ImageSourceConverter
类获取所需内容,例如:
img1.Source = (ImageSource)new ImageSourceConverter().ConvertFromString("/Assets/check.png");
它不适用于静态资源,但可能无论如何都会有用…:) i、 e.如何动态设置网格背景
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;
i、 e.如何动态设置应用的图标
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;
通用应用程序的
Media
命名空间不可用System.Windows.Media.ImageSourceConverter
这里是什么?对于“ImageSource”,您还需要包括“using System.Windows.Media;”。但“资源”在当前环境下仍然不可用。。。