0

I want to change image dynamically on a button. I think I have what is required to find the image. I have som resourcedictionary for the buttons here:

<BitmapImage x:Key="Mark1Empty" UriSource="Marks/Tom1.png"/>
<BitmapImage x:Key="Mark1Chosen" UriSource="Marks/Ny1.png"/>

Then afterwards, I create the button like this in XAML User control:

<Button x:Name="Mark1Button"
 Height="30" Width="40" Template="{StaticResource Mark1ButtonTemplate}"
cal:Message.Attach="[Event Click] = [Action SayHello($source, $this)]"/>

The ControlTemplate looks like this:

   <ControlTemplate x:Key="Mark1ButtonTemplate"  TargetType="{x:Type Button}">
        <Image Name="Mark1ButtonImage"  Source="{StaticResource Mark1Empty}" />
    </ControlTemplate>

After that. In C# code when I press the image. Then it triggers, but the image doesn't change. It is blank after clicking on the image.

    public void SayHello(object sender, object kravsource)
    {
        var selectedButton = sender as Button;
        if (selectedButton != null)
        {
            Image image = (Image)selectedButton.Template.FindName("Mark1ButtonImage", selectedButton);
            BitmapImage imagePicker = (BitmapImage)Application.Current.FindResource("Mark1Chosen");
            image.Source = new BitmapImage(new Uri(imagePicker.UriSource.ToString(), UriKind.RelativeOrAbsolute));
            image.Stretch = Stretch.Uniform;
        }
    }
Khiem-Kim Ho Xuan
  • 1,301
  • 1
  • 22
  • 45
  • 1
    Check out this method: http://stackoverflow.com/questions/5971300/programmatically-changing-button-icon-in-wpf/5973592#5973592 – d.moncada May 15 '15 at 14:52
  • 1
    Why aren't you just seeing `image.Source = imagePicker;`? Why try to create a whole new image? Are you sure that the resource URI is still valid relative to the location of the program when it runs? – Peter Duniho May 16 '15 at 05:53

0 Answers0