如何在代码中定义DataTemplate?

14

我如何在代码中(使用C#)创建一个DataTemplate,然后向该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>

我正在使用Silverlight。

3个回答

9
据我所知,在Silverlight中创建的唯一方法是使用XamlReader。基本上,您只需将XAML作为字符串传递给它,它就会返回一个。Byron的解决方案适用于WPF,但是(据我所知)Silverlight不支持FrameworkElementFactory
请注意选项#2,其中包括。
请参考Scott Morrison:在运行时定义Silverlight DataGrid列

+1 这是正确的。个人而言,我更喜欢使用 LinqToXml 对象来构建所需的 Xaml,但最终需要将结果字符串传递给 XamlReader 以便在程序中创建 DataTemplate。 - AnthonyWJones

4

您可以使用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;

2
OP说他正在使用Silverlight,据我所知它不支持FrameworkElementFactory。 - Josh

1

Microsoft在MSDN上有一篇很好的文章: "数据模板概述." 我建议从那里开始。

更新: 哦,算了吧。我看到你需要“在代码中”,我会把链接留在这里,供可能会遇到这篇文章的人使用。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接