Thriddas
Thriddas

Reputation: 45

WPF - Hosting a content control inside a Data Template via code

I'm trying to host a content control within a data template.

Exactly similar to this: Putting a ContentControl *inside* a WPF DataTemplate?

I was successful in doing it via XAML. I'd like to do the same via code.

I created a style :

<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>

and within a data template:

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

I tried doing this via code, but found nothing under DataTemplate that allows me to host a contentcontrol. Any suggestions?

Upvotes: 0

Views: 1045

Answers (1)

Sandeep Singh Rawat
Sandeep Singh Rawat

Reputation: 1647

Just copied from MSDN Forum but this should work. Havent tried it though.

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;

Also look at Create DataTemplate in code behind

Upvotes: 2

Related Questions