ho questo 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>
Inizialmente ho impostato l'immagine usando:
<Image Name="TypeIcon" HorizontalAlignment="Left" VerticalAlignment="Center"
Source="{StaticResource Customer}" Height="16" Width="16"/>
Sto cercando di cambiare TypeIcon
"S Source
a partire dal Cliente a Progetto in un metodo C #.
Ho provato a usare:
TypeIcon.Source = "{StaticResource Project}";
Ma ottengo questo errore:
Impossibile convertire implicitamente il tipo
string
aSystem.Windows.Media.ImageSource
Ho provato a definire l'immagine usando new ImageSource()
ma questo non funziona neanche.
Come posso cambiare l'immagine "s Source
programmaticamente in C #?
risposte:
13 per risposta № 1Dopo molto google, mentre scrivevo questa domanda, ho capito come farlo:
TypeIcon.Source = (ImageSource) Resources["Project"];
9 per risposta № 2
Non è per le risorse statiche ma forse sarà comunque utile ... :)
Ad esempio come impostare lo sfondo per Grid in modo dinamico
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;
cioè come impostare l'icona dell'app in modo dinamico
var idleIco = new Image
{
Source = new BitmapImage(
new Uri(
"pack://application:,,,/YourAppName;component/Images/idle.ico"))
};
SomeObjectYouAreUsingToSet.IconSource =idleIco.Source;
2 per risposta № 3
Puoi usare il ImageSourceConverter
classe per ottenere quello che vuoi, ad esempio:
img1.Source = (ImageSource)new ImageSourceConverter().ConvertFromString("/Assets/check.png");