The issue is following: we have a ListBox and for some reason we need to create a ListBox.ItemTemplate in code. In my case, I had to build a ListBox were each item is a button and I don’t know the template of it. I got it from other service. So there is no choose to do it on some other case, except of whole refactoring of architecture.
First of all, I’d like to maintain: don’t do it!
J It’s not a juke, there are lots of other possibility to avoid this situation, such as: use a converters/multy-converters, use predefined templates, eventually different styles for your ListBox. However, it’s not always possible.
First way: use a XamlLoader.
Just create necessary template like a string in code behind and load it
Note: don’t forget about necessary namespace. But in our case we don’t know what template we have.
Second way: use a ContentControl.
I used a ContentControl (I placed here a button with a DataTemplate) and Loaded event.
In test application I just loaded a ControlTemplate for button from Resources. Then added a button with click handler:
Eventually, this button I added like a DataTemplate to ListBoxItem.
Hope it’ll help.