2010-04-10 40 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

相關問題