如何在代码中定义DataTemplate?

如何在代码中创建DataTemplate (使用C#),然后向该DataTemplate添加控件?

           

我正在使用Sivlerlight。

据我所知,在Silverlight中创建DataTemplate的唯一方法是使用XamlReader 。 基本上你只需将XAML作为一个字符串传递给它,它会给你一个DataTemplate 。 Byron的解决方案适用于WPF,但Silverlight(据我所知)不支持FrameworkElementFactory

Scott Morrison:在运行时定义Silverlight DataGrid列

记下DataGridTemplateColumn的选项#2。

您可以使用FrameworkElementFactory添加像TextBlock这样的控件。 然后,您可以将TextBlock添加到DataTemplate的VisualTree。 像这样:

 //Create binding object and set as mode=oneway Binding binding = new Binding(); binding.Path = new PropertyPath("SomePropertyPathName"); binding.Mode = BindingMode.OneWay; //get textblock object from factory and set binding FrameworkElementFactory textElement = new FrameworkElementFactory(typeof(TextBlock)); textElement.SetBinding(TextBlock.TextProperty, binding); //apply textblock to datatemplate dataTemplate.VisualTree = textElement; 

微软在MSDN上发表了一篇很好的文章:“ 数据模板概述” 。 我会从那里开始。

更新 :呃,抓一点。 我读过你对“代码中”的要求。 我会在这里留下链接,以免谁有人偶然发现这篇文章。