0

I'm defining a DataGrid in my xaml, where each row represents a book, and each column a field associated to this book (similarly to a SQL table). I want the cell to appear a with a yellow background and bold fontweigth if and only if the user edited the field of the book corresponding to this cell.

This is my model classes:

public class EditableBook : INotifyPropertyChanged
{
    public EditableField<string> MA { get; }
    public EditableField<int> Numero { get; }
    public EditableField<string> Language { get; }
}

public class EditableField<T> : INotifyPropertyChanged
{
    private T _value;

    public T OriginalValue { get; }
    public T Value
    {
        get => _value;
        set
        {
            if (!value.Equals(_value))
            {
                _value = value;
                OnPropertyChanged(nameof(Value));
                OnPropertyChanged(nameof(IsEdited));
            }
        }
    }

    public void Restore()
    {
        Value = OriginalValue;
    }

    public bool IsEdited => !Equals(OriginalValue, _value);
}

In my xaml, I've bound my DataGrid to an ObservableCollection and I've defined a static resource

<DataGrid x:Name="MyDataGrid"
          AutoGenerateColumns="False"
          ItemsSource="{Binding Books}"> <!-- Books is the collection of books in the ViewModel class -->
    <DataGrid.Resources>
        <Style x:Key="ReusableElementStyle" TargetType="TextBlock">
            <Style.Triggers>
            <!-- Highlight if the value is edited -->
            <DataTrigger Binding="{Binding RelativeSource={RelativeSource AncestorType=DataGridCell}, Path=IsEdited}" Value="True">
                <Setter Property="FontWeight" Value="Bold" />
                <Setter Property="Background" Value="Yellow" />
            </DataTrigger>
            </Style.Triggers>
        </Style>
    </DataGrid.Resources>
    <DataGrid.Columns>
        <!-- Text Column -->
        <DataGridTextColumn Header="Matière"
           Binding="{Binding MA.Value}"
           Width="60"
           ElementStyle="{StaticResource ReusableElementStyle}"/>
    </DataGrid.Columns>
</DataGrid>

I keep getting this error:

BindingExpression path error: 'IsEdited' property not found

Questions:

  1. How can I bind a DataGridTextColumn to an EditableField so that its IsEdited property can be used in reusable styles?
  2. Is there a better way to handle styling DataGrid cells based on properties of custom data types without duplicating the logic for each column?

I've tried using various RelativeSource, using a converter and tweeking the Path but couldn't solve it.

1
  • MA.IsEdited should do as MA.Value does. Commented Jan 21 at 5:31

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.