I开发者_Python百科 need to do this in code, not XAML.
Its not possible to programmatically create the content of a data template in the same way you might create Controls and add them to a UserControl
.
Instead you will need to use System.Xml.Linq.XDocument
to construct the DataTemplate as XML with DataTemplate
being the root element. Once complete you can retrieve the XML string for the Root element and then use XamlReader.Load
to get a constructed DataTemplate
.
With a ListBox, you can specify a DataItemTemplate - just put whatever controls you want in that DataItemTemplate (e.g. you might want multiple TextBlocks), and bind them to whatever properties you want on the bound object.
To load the DataItemTemplate dynamically, you can use the same technique as illustrated in this blog post.
精彩评论