如何以编程方式将 C# 中的图像源设置为 XAML 静态资源?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18625086/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to set Image Source in C# to XAML Static Resource programmatically?
提问by Danny Beckett
I have this ResourceDictionary
in Main.xaml
:
我有这样ResourceDictionary
的Main.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>
I initially set the image using:
我最初使用以下方法设置图像:
<Image Name="TypeIcon" HorizontalAlignment="Left" VerticalAlignment="Center"
Source="{StaticResource Customer}" Height="16" Width="16"/>
I'm trying to change TypeIcon
's Source
from Customerto Projectin a C# method.
我正在尝试使用 C# 方法将TypeIcon
'sSource
从Customer更改为Project。
I've tried using:
我试过使用:
TypeIcon.Source = "{StaticResource Project}";
But I get this error:
但我收到此错误:
Cannot implicitly convert type
string
toSystem.Windows.Media.ImageSource
不能将类型隐式转换
string
为System.Windows.Media.ImageSource
I've tried defining the image using new ImageSource()
, but this doesn't work either.
我试过使用 定义图像new ImageSource()
,但这也不起作用。
How can I change the image's Source
programmatically in C#?
如何Source
在 C# 中以编程方式更改图像?
采纳答案by Danny Beckett
After much Googling, whilst writing this question, I figured out how to do it:
经过多次谷歌搜索,在写这个问题时,我想出了如何去做:
TypeIcon.Source = (ImageSource) Resources["Project"];
回答by Karthik Krishna Baiju
You can use the ImageSourceConverter
class to get what you want, for example:
您可以使用ImageSourceConverter
该类来获取您想要的内容,例如:
img1.Source = (ImageSource)new ImageSourceConverter().ConvertFromString("/Assets/check.png");
回答by Developer
It is not for static resources but perhaps will be useful anyway... :)
它不适用于静态资源,但无论如何可能会有用...... :)
i.e. how to set background for Grid dynamically
即如何动态设置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;
i.e. how to set icon of the app dynamically
即如何动态设置应用程序的图标
var idleIco = new Image
{
Source = new BitmapImage(
new Uri(
"pack://application:,,,/YourAppName;component/Images/idle.ico"))
};
SomeObjectYouAreUsingToSet.IconSource =idleIco.Source;