微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

以编程方式创建 GridViewColumn

如何解决以编程方式创建 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 举报,一经查实,本站将立刻删除。