Create a grid in WPF as Template programmatically

前端 未结 4 1904
太阳男子
太阳男子 2021-01-17 13:59

I want to create a basic user control with a style programmatically. In this style I want to add a Grid (no problem), but I can\'t add column definitions to thi

4条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-17 14:34

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

提交回复
热议问题