Create a grid in WPF as Template programmatically

醉酒当歌 提交于 2019-12-01 16:24:34
Pavan

FrameworkElementFactory has some custom logic for handling the ColumnDefinitions and RowDefinitions in a Grid. For those values, you treat them like children in the factory tree, for example:

FrameworkElementFactory gridFactory = new FrameworkElementFactory(typeof(Grid));

var column1 = new FrameworkElementFactory(typeof(ColumnDefinition));
column1.SetValue(ColumnDefinition.WidthProperty, new GridLength(1, GridUnitType.Auto));

var column2 = new FrameworkElementFactory(typeof(ColumnDefinition));
column2.SetValue(ColumnDefinition.WidthProperty, new GridLength(1, GridUnitType.Star));

gridFactory.AppendChild(column1);
gridFactory.AppendChild(column2);

you can simply add column definitions like this

XAML Code:

<Grid.ColumnDefinitions>
<ColumnDefinition Height="50"/>
<ColumnDefinition Height="100"/>
<ColumnDefinition Height="*"/>
</Grid.ColumnDefinitions>

C# Code:

ColumnDefinition c = new ColumnDefinition();
c.Width = new GridLength(50, GridUnitType.Pixel);

ColumnDefinition c1 = new ColumnDefinition();
c1.Width = new GridLength(100, GridUnitType.Pixel);

ColumnDefinition c2 = new ColumnDefinition();
c2.Width = new GridLength(0, GridUnitType.Star);

grMain.ColumnDefinitions.Add(c);
grMain.ColumnDefinitions.Add(c1);
grMain.ColumnDefinitions.Add(c2);

for more check here

//create grid 
            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);

            c = new FrameworkElementFactory(typeof(ColumnDefinition));
            c.SetValue(ColumnDefinition.WidthProperty, GridLength.Auto);
            grid.AppendChild(c);

            c = new FrameworkElementFactory(typeof(ColumnDefinition));
            c.SetValue(ColumnDefinition.WidthProperty, GridLength.Auto);
            grid.AppendChild(c);

You just need to change the last part of your code. See below,

Original Code:

        colDefinitions.AppendChild(c1);
        colDefinitions.AppendChild(c2);
        colDefinitions.AppendChild(c3);
        mainGrid.AppendChild(colDefinitions);

New Code:

        mainGrid.AppendChild(c1);
        mainGrid.AppendChild(c2);
        mainGrid.AppendChild(c3);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!