I'm writing a Silverlight application that requires me to dynamically create a ControlTemplate at runtime. Most of the solutions I've found involve creating a new开发者_开发问答 template for each case, but I have far too many cases to do this. How would I create a new ControlTemplate in C#?
You cannot create a ControlTemplate in Silverlight in C# alone. Unlike WPF (where you can set the VisualTree property), there is no property you can set that specifies the "content" of the ControlTemplate.
You can define your XAML as a string, and then load that dynamically in C# as explained by this blog post.
The code boils down to:
var template = (ControlTemplate)XamlReader.Load("<ControlTemplate " +
" xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"" +
" xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\">" +
" content here " +
"</ControlTemplate>");
精彩评论