2010-04-10 61 views
14

如何在代码中创建DataTemplate(使用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> 

我正在使用Sivlerlight。

回答

9

据我所知,只有这样,才能建立在Silverlight中DataTemplate是使用XamlReader。基本上你只要把它作为一个字符串传递给XAML,它就会给你一个DataTemplate。拜伦的解决方案将适用于WPF,但Silverlight(据我所知)不支持FrameworkElementFactory

Scott Morrison: Defining Silverlight DataGrid Columns at Runtime

注意到选项#2 DataGridTemplateColumn

+0

+1这是正确的。我个人更喜欢使用LinqToXml对象来构建所需的Xaml,但最终需要将结果字符串传递给XamlReader以编程方式创建DataTemplate。 – AnthonyWJones 2010-04-10 22:01:21

1

微软有一个好的文章了MSDN上: “Data Templating Overview。”我会从那里开始。

更新:嗯,从头开始。我读了你的要求“在代码中”。我会把这里的链​​接留在任何可能遇到这个帖子的人身上。

4

您可以添加使用FrameworkElementFactoryTextBlock控制。然后,您可以将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 2010-04-10 02:50:00

+0

所以他是,我的错。 – 2010-04-11 19:12:26

相关问题