We cannot new A datatemplate in code behind, otherwise it will popup an error.
There are two solutions to solve this problem, one is to define a datatemplate in the. XAML file as resources. Such:
<Resourcedictionary
Xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
Xmlns: x = "http://schemas.microsoft.com/winfx/2006/xaml"
Xmlns: L = "CLR-namespace: Local; Assembly = Local">
<L: negativevalueconveter X: Key = "converter"/>
<Datatemplate X: Key = "template">
<Textblock
TEXT = "{binding bindingpath }"
Tag = "{binding tag }"
Horizontalalignment = "stretch"
Foreground = "{binding bindingpath, converter = {staticresource converter }}"
Textdecorations = "underline"/>
</Datatemplate>
<Resourcedictionary/>
Make sure to replace the "L" with your own namespace and assembly.
The other solution is using xamlreader in code behind, such:
Stringbuilder sbtemp = new stringbuilder ();
Sbtemp. append ("<datatemplate ");
Sbtemp. append ("xmlns = 'HTTP: // schemas.microsoft.com/client/2007 '");
Sbtemp. append ("xmlns: x = 'HTTP: // schemas.microsoft.com/winfx/2006/xaml '");
Sbtemp. append ("xmlns: Local = 'clr-namespace: Test; Assembly = test> ");
Sbtemp. append ("<grid> ");
Sbtemp. append ("<grid. Resources> ");
Sbtemp. append ("<local: doubletostyleconverter X: Key = 'doubletostyleconverter '/> ");
Sbtemp. append ("</grid. Resources> ");
Sbtemp. append ("<textbox text = '{binding [" + bindingpath + "], mode = twoway }'");
Sbtemp. append ("isreadonly = 'true '");
Sbtemp. append ("foreground = \" {binding ["+ bindingpath +"], mode = twoway, converter = {staticresource doubletostyleconverter }}\"");
Sbtemp. append ("/> ");
Sbtemp. append ("</GRID> ");
Sbtemp. append ("</datatemplate> ");
Return (datatemplate) xamlreader. Load (sbtemp. tostring ());
1. Make sure to replace the "test" with your own namespace and assembly.