I don’t post in this section often because I don’t know the most common problems unless I receive an email from someone about a problem. You can understand the need with the number of results after searching about a specific problem. Many programmers have this issue, they find difficulties when they try to change the source of the image using datatriggers. This is because they try to put only the change in the trigger. In order for this to work you should also include the source property in the style as a setter for the default image source instead of initializing it in your image. If you initialize the source in the image tag like this <Image Source=”/Resources/OK.png” /> it will not work.

The style that changes the image source with datatrigger:

  <Style TargetType="{x:Type Image}">
    <Setter Property="Source" Value="/Resources/OK.png" />
    <Style.Triggers>
      <DataTrigger Binding="{Binding IsFalse}" Value="True">
        <Setter Property="Source" Value="/Resources/Error.png" />
      </DataTrigger>
    </Style.Triggers>
  </Style>

The image sources and the binding path are just samples and you should change them in your code. I just say that because some time ago someone sent me an (angry) email saying that the code I provided was not working. After few emails I realized that he just copied and pasted the code and he was using the sample names. If you used this style and the image is not always changing but only some times check your binding and your property. You might need to implement INotifyPropertyChanged. I hope that this post will help someone some day.

WPF – Styles – Change Image Source

Leave a Reply

Your email address will not be published.