How to change the source of an image control from a Resourcedictionary

Asked

Viewed 344 times

2

I have the next Resourcedictionary:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                xmlns:local="clr-namespace:semaforo.imagens">
<BitmapImage x:Key="semaforoVerde" UriSource="green.png" />
<BitmapImage x:Key="semaforoAmarelo" UriSource="yellow.png" />
<BitmapImage x:Key="semaforoVermelho" UriSource="red.png" />

Whenever I want to change the color of the traffic light I do so:

semaforo.Source = new BitmapImage(new Uri("pack://application:,,,/imagens/red.png"));

Instead of the Uri used above it is possible to use something simpler like x:Key="semaforoVerde" or something like that?

  • Do you want to do this in the code or in the shaman?

  • In the code. I’m still using the syntax of ""pack://application:,,,/images/red.png" without being sure what it is!

1 answer

2


Via code you can access Resources declared/defined in a Control in two ways:

1 - Using the property Resources

semaforo.Source = (BitmapImage) Control.Resources["semaforoVerde"];

2 - Using the method Findresource()

semaforo.Source = (BitmapImage) Control.FindResource("semaforoVerde");

Substitute Control by the name of the object where the Resource.
If at the application level use Application.Current

  • 1

    In my case it was Application.Current ... worked perfectly and is simpler than I was doing.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.