以编程方式创建 GridViewColumn

问题描述

我正在以编程方式创建 GridViewColumns。我的列很简单:一个包含 TextBox 的 Grid。我设置了 Grid.Margin 和 TextBox 的 Tag 和 Style 属性。我希望我的 GridViewColumn 看起来像下面的 XAML:

<GridViewColumn Header="MyHeader">
    <GridViewColumn.CellTemplate>
        <ItemContainerTemplate>
            <Grid Margin="-6,-6,0">
                <TextBox Tag="0" Style="{StaticResource PassFailStyle}"/>
            </Grid>
        </ItemContainerTemplate>
    </GridViewColumn.CellTemplate>
</GridViewColumn>   

这是我的风格:

<Style x:Key="PassFailStyle" targettype="{x:Type TextBox}">
    <Setter Property="Text">
        <Setter.Value>
            <MultiBinding Converter="{StaticResource ResourceKey=TestResultConverter}">
                <Binding Path="CycleTestResults"/>
                <Binding RelativeSource="{x:Static RelativeSource.Self}" Path="Tag"/>
            </MultiBinding>
        </Setter.Value>
    </Setter>

    <Setter Property="HorizontalContentAlignment" Value="Center"/>

    <Setter Property="FontSize" Value="18"/>

    <Style.Triggers>
        <DataTrigger Binding="{Binding RelativeSource={x:Static RelativeSource.Self},Path=Text}" Value="Pass">
            <Setter Property="Background" Value="LightGreen"></Setter>
        </DataTrigger>

        <DataTrigger Binding="{Binding RelativeSource={x:Static RelativeSource.Self},Path=Text}" Value="Fail">
            <Setter Property="Background" Value="Red"></Setter>
        </DataTrigger>

        <DataTrigger Binding="{Binding RelativeSource={x:Static RelativeSource.Self},Path=Text}" Value="Skip">
            <Setter Property="Background" Value="Yellow"></Setter>
        </DataTrigger>
    </Style.Triggers>
</Style>

这是我的代码

private GridViewColumn CreateColumn(string header,int tag)
{
    GridViewColumn newColumn = new GridViewColumn();
    newColumn.Header = header;

    FrameworkElementFactory textBoxFactory = new FrameworkElementFactory(typeof(TextBox));

    Style style = FindResource("PassFailStyle") as Style;
    textBoxFactory.SetValue(StyleProperty,style);

    textBoxFactory.SetValue(TagProperty,tag);

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

    // negative margin makes TextBox fill Grid cell width
    gridFactory.SetValue(MarginProperty,new Thickness(-6,0));
    gridFactory.AppendChild(textBoxFactory);

    DataTemplate template = new DataTemplate();
    template.VisualTree = gridFactory;            
            
    newColumn.CellTemplate = template;            

    return newColumn;
}

注意样式中的 MultiBinding 和转换器。问题是 MultiBinding 的第二个值 (Tag) 在到达我的转换器时为空。如果我注释掉将样式添加到 TextBox代码,则 Tag 会完好无损地到达转换器(非空)。

我知道样式可以正常工作,因为我首先编写了 XAML,现在才以编程方式创建它。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)