代码之家  ›  专栏  ›  技术社区  ›  Gilles

如何在动态网格中应用数据模板?

  •  1
  • Gilles  · 技术社区  · 14 年前

    我有一个网格。网格的列在运行时根据用户的选择自动生成。

    如果内容是负数,我需要网格中的单元格为红色。

    我创建了一个DataTemplateSelector。正确调用了DataTemplateSelector get,如果单元格为负数,则返回我的模板。

    因为我的列是自动生成的,所以我不能简单地在模板的绑定中放置正确的字段。

                <DataTemplate x:Key="MontantNegatifTemplate">                    
                    <TextBlock Foreground="Red" Text="{Binding}" />
                </DataTemplate>
    

    如果我做这样的模板,文本就是网格所绑定对象的名称。

    如果我做类似的事情:

                <DataTemplate x:Key="MontantNegatifTemplate">                    
                    <TextBlock Foreground="Red" />
                </DataTemplate>
    

    该单元格为空,因为文本块似乎覆盖了标准的自动生成的单元格。

    有什么方法可以让这个工作吗?我应该用另一种方法吗?

    1 回复  |  直到 14 年前
        1
  •  0
  •   Gilles    14 年前

    我终于明白了我的问题。

    我需要使用样式选择器而不是DataTemplateSelector。

    同样,我需要在网格资源中定义样式而不是数据模板。

    <style:NegativeStyleSelector x:Key="NegativeStyleSelector">
                        <style:NegativeStyleSelector.NegativeStyle>
                            <Style TargetType="GridViewCell">
                                <Setter Property="Foreground" Value="Red"/>
                            </Style>
                        </style:NegativeStyleSelector.NegativeStyle>
                    </style:NegativeStyleSelector>