如何设置DataGridTextColumn文本颜色?

Ars*_*ray 12 c# wpf xaml wpfdatagrid datagridtextcolumn

我正在尝试更改DataGridTextColumn的颜色.

这是我正在做的事情:

<DataGridTextColumn 
    Header="Status" 
    Binding="{Binding IsActive, 
               Converter= {StaticResource BoolToStatusConverter}}"
    Foreground="{Binding Path=IsActive,
               Converter={StaticResource BoolToColorConverter}}"/>
Run Code Online (Sandbox Code Playgroud)

文本设置正确,但颜色不会改变,我收到以下错误:

System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or 
FrameworkContentElement for target element. BindingExpression:Path=IsActive; 
DataItem=null; target element is 'DataGridTextColumn' (HashCode=40349079); target 
property is 'Foreground' (type 'Brush')
Run Code Online (Sandbox Code Playgroud)

我该怎么做才能工作?

Phi*_*hil 13

您需要为列的CellStyle指定带有DataTrigger的样式.例如

<Page.Resources>
    <Style TargetType="DataGridCell" x:Key="ActiveCellStyle">
        <Setter Property="Foreground" Value="Blue"/>
        <Style.Triggers>
            <DataTrigger Binding="{Binding IsActive}" Value="{x:Null}">
                <Setter Property="Foreground" Value="Green"/>
            </DataTrigger>
            <DataTrigger Binding="{Binding IsActive}" Value="True">
                <Setter Property="Foreground" Value="Red"/>
            </DataTrigger>
        </Style.Triggers>
    </Style>
    <Converters:BoolToTextConverter 
        x:Key="BoolToStatusConverter" 
        TargetCondition="True" 
        IsMatchValue="It's active" 
        IsNotMatchValue="It's dead" />
</Page.Resources>
<Grid>
    <DataGrid ItemsSource="{Binding Items}" AutoGenerateColumns="False">
        <DataGrid.Columns>
            <DataGridTextColumn 
                Header="Status" 
                Binding="{Binding IsActive, 
                    Converter={StaticResource BoolToStatusConverter}}" 
                CellStyle="{StaticResource ActiveCellStyle}"/>
        </DataGrid.Columns>
    </DataGrid>
</Grid>
Run Code Online (Sandbox Code Playgroud)


A.R*_*.R. 8

虽然从技术上讲不是DataGridTextColumn,但这是我通常做的事情:

<DataGridTemplateColumn Header="Status" SortMemberPath="Status">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Status}" Foreground="{Binding Status, Converter={StaticResource StatusToSolidColor}}" />
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
Run Code Online (Sandbox Code Playgroud)

我得到了我想要的datacontext,我可以在应用程序的其余部分中重用我可能已经存在的转换器.此外,我不必硬编码/维护一组额外的样式和数据触发器来获得所需的效果.