I have this ResourceDictionary
in 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 Customer to Project in a C# method.
I've tried using:
TypeIcon.Source = "{StaticResource Project}";
But I get this error:
Cannot implicitly convert type
string
toSystem.Windows.Media.ImageSource
I've tried defining the image using new ImageSource()
, but this doesn't work either.
How can I change the image's Source
programmatically in C#?
经过大量的谷歌搜索,在写这个问题时,我想出了如何做到这一点:
TypeIcon.Source = (ImageSource) Resources["Project"];
It is not for static resources but perhaps will be useful anyway... :)
ie how to set background for Grid dynamically
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;
ie 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;
您可以使用ImageSourceConverter
类来获取所需内容,例如:
img1.Source = (ImageSource)new ImageSourceConverter().ConvertFromString("/Assets/check.png");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.