I'm trying to change the text colour in a datagrid
depending on a bool
in my model using a converter but I get the following error.
System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or FrameworkContentElement for target element. BindingExpression:Path=DiameterCustom; DataItem=null; target element is 'DataGridTextColumn' (HashCode=7886611); target property is 'Foreground' (type 'Brush')
Does anyone know why this is?
My xaml is as follows:
<UserControl.Resources>
<conv:UnitConverter x:Key="UnitConverter"></conv:UnitConverter>
<conv:CustomColourConverter x:Key="CustomColourConverter"></conv:CustomColourConverter>
</UserControl.Resources>
<DataGridTextColumn
Header="Diameter 
(mm)"
Binding="{Binding Diameter, Mode=TwoWay, StringFormat={}{0:n0}, Converter={StaticResource UnitConverter}, ConverterParameter=1000}"
Foreground="{Binding DiameterCustom, Converter={StaticResource CustomColourConverter}}"/>
This is my converter:
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
bool v = (bool)value;
if (v == true)
{
//return return System.Windows.Media.Brushes.Red;
return new SolidColorBrush(Colors.Red);
}
//return return System.Windows.Media.Brushes.Blue;
return new SolidColorBrush(Colors.Blue);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
and just for completeness, here is my model property:
private bool diameterCustom;
public bool DiameterCustom
{
get { return diameterCustom; }
set { SetAndNotify(ref this.diameterCustom, value); }
}
Note, the data binding for Diameter and the unit converter work fine.
CodePudding user response:
To change the text colour cell by cell the following solution worked:
<DataGridTextColumn
Header="Diameter 
(mm)"
Binding="{Binding Diameter, Mode=TwoWay, StringFormat={}{0:n0}, Converter={StaticResource UnitConverter}, ConverterParameter=1000}">
<DataGridTextColumn.ElementStyle>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="Foreground" Value="{Binding DiameterCustom, Converter={StaticResource CustomColourConverter}}"/>
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>