初学WPF , 希望对DataGrid 中所属的一个Column名下的值的颜色动态修改
<DataGridTextColumn Header=”隐含回购利率(%)” Binding=”{Binding ImpRepo, StringFormat={}{0:f4}}” MinWidth=”60″ IsReadOnly=”True” />
但是使用如下语句并没有起作用:
Foreground=”{Binding Path=ImpRepo,Converter={StaticResource IRRColorConvert}}”
IRRColorConvert定义在XAML前方:
<UserControl.Resources>
<ResourceDictionary>
<local:IRRColorConvert x:Key=”IRRColorConvert”/>
………..
IRRColorConvert代码如下:
class IRRColorConvert : IValueConverter
{
public object Convert(object value, Type typeTarget, object param, CultureInfo culture)
{
double dValue = (double)value;
byte r, g, b = 0;
if (dValue >= 0)
{
if (dValue >= 5)
r = 254;
else
r = (byte)(int)(norlib.Maths.GetValue(new double[] { 0, 5 }, dValue, new double[] { 200, 255 }));
g = 89;
b = 61;
}
else
{
r = 56;
if (dValue <= -30)
g = 150;
else
g = (byte)(int)(norlib.Maths.GetValue(new double[] { -30, 0 }, dValue, new double[] { 150, 255 }));
b = 61;
}
return new SolidColorBrush(Color.FromRgb(r, g, b));
}
public object ConvertBack(object value, Type typeTarget, object param, CultureInfo culture)
{
return "";
}
}
后来才知道 Foreground 不是 DataGridTextColumn 的
依赖项属性
关于这些概念请参看如下链接:
http://www.cnblogs.com/axzxs2001/archive/2010/04/25/1719857.html
http://blog.csdn.net/datoumimi/article/details/8033682
解决的办法如下,使用DataGridTemplateColumn+TextBlock 代替DataGridTextColumn
因为TextBlock的Foreground是Dependency Proeprty
可以比较MSDN:
DataGridTextColumn:
TextBlock:
http://msdn.microsoft.com/en-us/library/system.windows.controls.textblock.foreground.aspx
解决代码如下:
<DataGridTemplateColumn Header="隐含回购利率(%)" MinWidth="70" IsReadOnly="True">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding ImpRepo, StringFormat={}{0:n2},UpdateSourceTrigger=PropertyChanged}" Foreground="{Binding Path=ImpRepo,Converter={StaticResource IRRColorConvert}}"/>
</StackPanel>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
国外对此问题的一些说明:
http://stackoverflow.com/questions/5926849/datagridtextcolumn-how-to-bind-isreadonly
希望可以帮到大家
转载于:https://www.cnblogs.com/norsd/p/6359388.html