wpfcontroltemplateframeworkelementfactory

Setting ControlTemplate in code [WPF]


How can I set Grid object with some UI elements in ControlTemplate? I try use this code, but I don't understand how to set Grid object to FrameworkElementFactory object. Thanks

    ControlTemplate CellControlTemplate = new ControlTemplate(); // my control template
    Grid CellGrid = new Grid(); // my grid (I want add it to my control template
    FrameworkElementFactory root = new FrameworkElementFactory(typeof(Grid));
// ???
    CellControlTemplate.VisualTree = root;

I need it for replacing my xaml-designed style in code behind:

<Style TargetType="{x:Type igDP:CellValuePresenter}" x:Key="PStyle">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type igDP:CellValuePresenter}">
                    <Grid Margin="4">
                        <Grid.RowDefinitions>
                            <RowDefinition />
                        </Grid.RowDefinitions>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition />
                            <ColumnDefinition Width="Auto"/>
                            <ColumnDefinition Width="Auto"/>
                        </Grid.ColumnDefinitions>
                        <TextBlock Grid.Row="0" Grid.RowSpan="2" Grid.Column="0"
                                           FontWeight="DemiBold"
                                           FontSize="18"
                                           VerticalAlignment="Center"
                                           Text="{Binding Path=DataItem.DINAMIC_COLUMN}"/>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

I must do it, because I want change binding path for textbox in runtime from code. Do you know others ways? Thanks.


Solution

  • Here is solution:

    var grid = new FrameworkElementFactory(typeof(Grid));
    // assign template to grid 
    CellControlTemplate.VisualTree = grid;
    // define grid's rows 
    var r = new FrameworkElementFactory(typeof(RowDefinition));
    grid.AppendChild(r);
    // define grid's columns
    var c = new FrameworkElementFactory(typeof(ColumnDefinition));
    grid.AppendChild(c);
    //... etc
    

    Thanks all.