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

2

I have the following 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 semaphore I proceed like this:

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="traffic light" or something like this?

    
asked by anonymous 03.04.2016 / 20:08

1 answer

2

Via code you can access declared / defined resources in two ways:

1 - Using the Resources

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

2 - Using the FindResource ( )

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

Replace Control with its object name where the resource was declared / defined.
If it was at the application level use Application.Current

    
03.04.2016 / 21:16