Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Wpf 如何在动态网格中应用数据模板?_Wpf_Datatemplate_Datatemplateselector - Fatal编程技术网

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

Wpf 如何在动态网格中应用数据模板?,wpf,datatemplate,datatemplateselector,Wpf,Datatemplate,Datatemplateselector,我有一个网格。网格的列在运行时根据用户的选择自动生成 如果内容为负数,我需要网格中的单元格为红色 我已经创建了一个DataTemplateSelector。正确调用DataTemplateSelector get,如果单元格为负数,则返回my template 因为我的列是自动生成的,所以我不能简单地将正确的字段放在模板的绑定中 <DataTemplate x:Key="MontantNegatifTemplate">

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

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

我已经创建了一个DataTemplateSelector。正确调用DataTemplateSelector get,如果单元格为负数,则返回my template

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

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

如果我使用这样的模板,文本就是网格绑定到的对象的名称

如果我这样做:

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

单元格为空,因为Textblock似乎覆盖了标准自动生成的单元格


有没有办法让这一切顺利进行?我应该使用另一种方法吗

我终于找到了回答我问题的答案

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

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

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