使用FrameworkElementFactory在WPF中创建网格

时间:2017-07-11 13:58:35

标签: c# wpf xaml

简而言之,我将静态XAML描述UI制作成动态创建的UI。以下是我要在c#中复制的XAML代码:

<GridViewColumn.HeaderTemplate>
    <DataTemplate>
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto" />
                <ColumnDefinition Width="*" />
            </Grid.ColumnDefinitions>
            <CheckBox Grid.Column="0"
                      Margin="4,0,5,0"
                      VerticalAlignment="Center"
                      IsChecked="{Binding Path=DataContext.AreAllSelected,
                                          RelativeSource={RelativeSource AncestorType=ListView},
                                          Mode=OneWay}"
                      Command="{Binding Path=DataContext.ChangeAllSourcesSelection,
                                        RelativeSource={RelativeSource AncestorType=ListView}}" />
            <TextBlock Grid.Column="1"
                       VerticalAlignment="Center"
                       UI:DisplayedObjectProperties.DisplayedObject="{Binding}" />
        </Grid>
    </DataTemplate>
</GridViewColumn.HeaderTemplate>

以下是我的想法:

GridViewColumn col = new GridViewColumn();

DataTemplate template = new DataTemplate();

FrameworkElementFactory gridFactory = new FrameworkElementFactory(typeof(Grid));
FrameworkElementFactory col1 = new FrameworkElementFactory(typeof(ColumnDefinition));
FrameworkElementFactory col2 = new FrameworkElementFactory(typeof(ColumnDefinition));

col1.SetValue(ColumnDefinition.WidthProperty, new GridLength(1, GridUnitType.Auto));
col2.SetValue(ColumnDefinition.WidthProperty, new GridLength(1, GridUnitType.Star));
gridFactory.AppendChild(col1);
gridFactory.AppendChild(col2);

FrameworkElementFactory boxFactory = new FrameworkElementFactory(typeof(CheckBox));
boxFactory.SetValue(Grid.ColumnProperty, 1);
boxFactory.SetValue(FrameworkElement.VerticalAlignmentProperty, VerticalAlignment.Center);
FrameworkElementFactory tBlockFactory = new FrameworkElementFactory(typeof(TextBlock));
tBlockFactory.SetValue(Grid.ColumnProperty, 2);
tBlockFactory.SetValue(FrameworkElement.VerticalAlignmentProperty, VerticalAlignment.Center);
tBlockFactory.SetValue(TextBlock.TextProperty, LanguageManager.Parse(columnVM.ColumnName));

gridFactory.AppendChild(boxFactory);
gridFactory.AppendChild(tBlockFactory);
template.VisualTree = gridFactory;

col.HeaderTemplate = template;

然而,由于CheckBox和TextBlock似乎都在同一列中,因此这并没有给我带来理想的效果。如何将每个分配给相应的列?正如你所看到的,我做了一些奇怪的补充,因为我不知道我在做什么。

Here is the result I want:

1 个答案:

答案 0 :(得分:1)

您应该将Grid.Column的{​​{1}}附加属性设置为1:

TextBlock

没有理由为tBlockFactory.SetValue(Grid.ColumnProperty, 1); 设置属性,因为它应该具有默认值0。