2013-03-06 39 views
0

我試圖託管數據模板內的內容控件。WPF - 通過代碼託管數據模板內的內容控件

正是與此類似: Putting a ContentControl *inside* a WPF DataTemplate?

我成功地通過XAML這樣做。我想通過代碼做同樣的事情。

我創建了一個風格:

<Style x:Key="radioButtonAddtruefalse"> 
    <Setter Property="Control.Template"> 
    <Setter.Value> 
     <ControlTemplate> 
     <StackPanel Orientation="Horizontal"> 
      <RadioButton Content="True" IsChecked="{Binding Value}"></RadioButton> 
      <RadioButton Content="False" IsChecked="{Binding Value, Converter={StaticResource _invertedBooleanConverter}}"></RadioButton> 
     </StackPanel> 
     </ControlTemplate> 
    </Setter.Value> 
    </Setter> 
</Style> 

和數據模板中:

   <DataTemplate> 
        <ContentControl Style="{StaticResource radioButtonAddtruefalse}"> /ContentControl> 
       </DataTemplate> 

我試着通過代碼實現這一點,但發現的DataTemplate下沒有什麼可以讓我舉辦一個ContentControl中。有什麼建議麼?

+1

看 http://stackoverflow.com/questions/5471405/create-datatemplate-in-code-behind – 2013-03-06 11:14:47

回答

1

剛剛從MSDN Forum複製,但這應該工作。沒有嘗試過。

FrameworkElementFactory fef = new FrameworkElementFactory(typeof(TextBlock)); 

Binding placeBinding = new Binding(); 

fef.SetBinding(TextBlock.TextProperty, placeBinding); 

placeBinding.Path = new PropertyPath("Name"); 

dataTemplate = new DataTemplate(); 

dataTemplate.VisualTree = fef; 

也期待在 Create DataTemplate in code behind

+0

感謝您的答覆。在xaml中完成內容控制時,並不真正出現在模板的可視樹中。它在那裏是一個孩子......找到了解決方法。 (並非特定於上述討論,因此未納入)。但我確實瞭解了FrameworkElementFactory。謝謝。 – Thriddas 2013-03-06 12:39:39

+0

好的。再試一次。作品。謝謝。 – Thriddas 2013-03-06 13:14:34