2012-04-29 39 views
3
<DataTemplate> 
    <TextBlock x:Name="Txt" Text="{Binding fieldA}" /> 
</DataTemplate> 

我想通过编程方式完成上述XAML的功能(对于XAML,我只显示了相关位)。到目前为止,我有:以编程方式将TextBlock添加到DataTemplate

DataTemplate newDataTemplate = new DataTemplate(); 
TextBlock newTextBlock = new TextBlock(); 
newTextBlock.SetBinding(TextBlock.TextProperty, new Binding("fieldA")); 
newTextBlock.Name = "txt"; 

所以我现在该如何将TextBlock添加到DataTemplate中..即我想要做的事,如:

newDataTemplate.children.Add(TextBlock) 

回答

7
var newTextBlock = new FrameworkElementFactory(typeof(TextBlock)); 
newTextBlock.Name = "txt"; 
newTextBlock.SetBinding(TextBlock.TextProperty, new Binding("fieldA")); 
DataTemplate newDataTemplate = new DataTemplate(){VisualTree = newTextBlock}; 

我想你应该看看这个问题。

How do I create a datatemplate with content programmatically?

+0

这是行不通的.. TextBlock的从来没有因此导致的DataTemplate中的树肯定是有办法只有巴掌的TextBlock到DataTemplate中的树。 – jsj 2012-04-29 06:55:59

+1

@ trideceth12:顺便说一下,[这是弃用](http://msdn.microsoft.com/en-us/library/system.windows.frameworkelementfactory.aspx)。 – 2012-07-23 04:53:38

相关问题