views:

25

answers:

1

How do I recreate the following XAML databinding in code? I have most of it except for the DataTemplate definition.

Here is an example of the DataBinding in XAML

    <GridViewColumn Width="140" Header="Name">
        <GridViewColumn.CellTemplate>
            <DataTemplate>
                <TextBox Text="{Binding Path=Label}" />
            </DataTemplate>
        </GridViewColumn.CellTemplate>
    </GridViewColumn>

Here is the code I have so far:

return new GridViewColumn()
        {
            Header = header,
            Width = width,
            DisplayMemberBinding = new System.Windows.Data.Binding(bindingProperty)
        };

The problem is, how did I set the CellTemplate for the DataTemplate through code?

A: 

For anyone interested, here is the solution:

private GridViewColumn GetGridViewColumn(string header, double width, string bindingProperty, Type type)
    {
        GridViewColumn column = new GridViewColumn();
        column.Header = header;

        FrameworkElementFactory controlFactory = new FrameworkElementFactory(type);

        var itemsBinding = new System.Windows.Data.Binding(bindingProperty);
        controlFactory.SetBinding(TextBox.TextProperty, itemsBinding);

        DataTemplate template = new DataTemplate();
        template.VisualTree = controlFactory;

        column.CellTemplate = template;
        return column;
    }
Chris