C# 如何在代码中定义数据模板?
如何在代码中创建C# 如何在代码中定义数据模板?,c#,silverlight,datagrid,silverlight-3.0,datatemplate,C#,Silverlight,Datagrid,Silverlight 3.0,Datatemplate,如何在代码中创建DataTemplate(使用C#),然后向该DataTemplate添加控件 <data:DataGrid.RowDetailsTemplate> <DataTemplate> <Border> <Border Margin="10" Padding="10" BorderBrush="SteelBlue" BorderThickness="3" Cor
DataTemplate
(使用C#),然后向该DataTemplate
添加控件
<data:DataGrid.RowDetailsTemplate>
<DataTemplate>
<Border>
<Border Margin="10" Padding="10" BorderBrush="SteelBlue"
BorderThickness="3" CornerRadius="5">
<TextBlock Text="{Binding Description}" TextWrapping="Wrap"
FontSize="10">
</TextBlock>
</Border>
</Border>
</DataTemplate>
</data:DataGrid.RowDetailsTemplate>
我正在使用Sivlerlight。微软在MSDN上有一篇好文章:“。我将从那里开始
更新:呃,划掉它。我仔细阅读了您对“in-code”的要求。我将把链接留在这里,让可能偶然发现这篇文章的人看看。您可以使用
FrameworkElementFactory
添加类似文本块的控件。然后,您可以将TextBlock
添加到DataTemplate
的可视化树中。像这样:
//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;
据我所知,在Silverlight中创建数据模板的唯一方法是使用。基本上,您只需将XAML作为字符串传递给它,它将返回一个DataTemplate
。Byron的解决方案将适用于WPF,但Silverlight(据我所知)不支持FrameworkElementFactory
注意DataGridTemplateColumn
的选项2,OP说他使用的是Silverlight,据我所知,Silverlight不支持FrameworkElementFactory。+1这是正确的。我个人更喜欢使用LinqToXml对象来构建所需的Xaml,但最终需要将结果字符串传递给XamlReader,以编程方式创建数据模板。