admin管理员组

文章数量:1203391

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.

本文标签: mvvmC WPF How to change a cell39s FontWeight and Background based on its new valueStack Overflow