I have a collection of objects bound to a hierarchical data template, each of my objects have a property on them (lets call it Property “A”) that is of a certain type. This type varies among each of the objects.
If the data template contains an image and some text, what would be the best way to change the image that is displayed in the template based on the type of property “A”.
I know I could just stick this into a converter and do the binding translation manually in code, but with all the binding facilities available in WPF, I think theres probably a better way.
It’s pretty simple to do this within your data template, if you create local data templates and use a
ContentPresenter. This template presents objects of typeMyObject, displaying an image whose source is determined by the type of theAproperty next to aTextBlockthat displays the content of theTextproperty:If you want to use styles to do this instead, you’re going to run into a problem, because data triggers want to look at property values, and the type of the
Aproperty is not, itself, exposed as a property.Unless, of course, you implement one:
(You’ll also need to raise
PropertyChangedforATypewhen the value ofAchanges.) Once you’ve done this, you should be able to implement a data trigger in a style, e.g.: