It’s quite easy to do this. What I suggest you do is declare the template in XAML (as that is the best place to do it), then reference it in code-behind.
Have a look at How to set Style Setter Properties in code behind? which links to How can I access ResourceDictionary in wpf from C# code?.
Alternatively, you can declare your template in a string in code, and then use XamlReader.Load to create it.
Please login first to submit.