I have a WPF app in VS2015. It's been developed as MVVM with nothing in the code-behind classes.
It has a user control containing a datagrid. I would like the background colour of any edited cell to be changed from white to red. I have a button bound to a method in the view model that applies the changed data to a database.
My problem is the binding of the Background property of the datagrid column.
My ViewModel contains:
private ObservableCollection<ComparisonRec> _piToAccessFilteredRecs;
The ComparisonRec implements ClientEntityBase
public class ComparisonRec : ClientEntityBase
This has an IsDirty property
I have the following ValueConverter class:
public class DirtyToBrushConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
Brush ret;
if ((bool)value == true)
{
ret = Brushes.Red;
}
else
{
ret = Brushes.White;
}
return ret;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotSupportedException();
}
}
The data context for my user control is set as follows:
<UserControl.DataContext>
<local:CompareUCViewModel />
</UserControl.DataContext>
In the DataGrid I have the binding:
ItemsSource="{Binding PiToAccessFilteredRecs}"
For the DataGridTextColumn that I need to highlight a change, I have the following binding:
Binding="{Binding Path=Access_Notes, Mode=TwoWay, UpdateSourceTrigger=LostFocus}">
This works fine to display the data. To try and get the highlighting, I added the following:
<DataGridTextColumn.ElementStyle>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="Background" Value="{Binding Access_Notes.IsDirty, Converter={StaticResource DirtyToBrushConverter}}" />
</Style>
</DataGridTextColumn.ElementStyle>
It's not working :( I see the following in the output window for each row displayed:
System.Windows.Data Error: 40 : BindingExpression path error: 'IsDirty' property not found on 'object' ''String' (HashCode=577941586)'. BindingExpression:Path=Access_Notes.IsDirty; DataItem='ComparisonRec' (HashCode=27207830); target element is 'TextBlock' (Name=''); target property is 'Background' (type 'Brush')
Can anyone see where I went wrong please?
EDIT As per @XAMIMAX suggestion, if I change binding to:
<Setter Property="Background" Value="{Binding Access_Notes
The the string value of Access_Notes (the content that would be displayed in the grid cell) is passed to the value converter and an exception is thrown because this can't be cast to (bool)
Access_Notes
and analyse it in your converter and see what you get? – XAMlMAX