首先根据条件写好颜色转换器,代码如下:
using System; using System.Windows; using System.Globalization; using System.Windows.Data;//有这句才能识别IvalueConverter using System.Collections.Generic; using BridgeProject.WebService.DAL; using System.Linq; using System.Text; namespace name1 { [ValueConversion (typeof(string),typeof(string))] class ColorConverter: IValueConverter { public object Convert(object value, Type typeTarget, object param, CultureInfo culture) { string strValue = value.ToString(); if (strValue.IndexOf('/') > 0) { String[] ss = strValue.Split('/'); if (ss[1] == "安全") return "Green"; if (ss[1] == "低偏压"||ss[1]=="高偏压") return "Orange"; return "Red"; } return "Black"; } public object ConvertBack(object value, Type typeTarget, object param, CultureInfo culture) { return ""; } } }
然后记得在xaml文件中进行资源声明
xmlns:local="clr-namespace:name1" <Window.Resources> <!--颜色转换器--> <local:ColorConverter x:Key="ColorConverter"/> </Window.Resources>
最后将转换器绑定到datagrid的相应单元格中:
<DataGrid x:Name="DataGrid_SafetyManagement_StateTable" AutoGenerateColumns="False" Background="{x:Null}" IsReadOnly="True" Visibility="Hidden" > <DataGrid.Columns> <DataGridTemplateColumn Header="col1" Width="Auto" IsReadOnly="True" > <DataGridTemplateColumn.CellTemplate> <DataTemplate> <TextBlock HorizontalAlignment="Center" Text="{Binding col1}" Foreground="{Binding Path=col1,Converter={StaticResource ColorConverter} }" /> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> <DataGridTemplateColumn Header="col2" Width="Auto" IsReadOnly="True" > <DataGridTemplateColumn.CellTemplate> <DataTemplate> <TextBlock HorizontalAlignment="Center" Text="{Binding col2}" Foreground="{Binding Path=col2,Converter={StaticResource ColorConverter} }" /> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> </DataGrid.Columns> </DataGrid>