mardi 15 septembre 2020

Recognise when CheckBox_Checked event is fired cause of binding

I apologize if this has been asked before, but i couldn't find anything helpful.

I have the following class

public class NumberOfInterest
{
    public bool HasChanged { get; set; } = false;
    public bool Prop1 { get; set; }
    public bool Prop2 { get; set; }
    ---
}

In my user control i have a DataGrid that use as item source an ObservableCollection<NumberOfInterest>. In this grid i have 2 CheckBox columns binded respectively to Prop1 and Prop2

Finally the property HasChanged of each NumberOfInterest should be set to true when a change from its initial state happes (i.e Prop1 or Prop2 change)

the property HasChanged is used in a Command in the CanExecute event in the following way

    public ICommand Save
    {
        get
        {
            save = new RelayCommand(() => SaveChanges(), () => NumbSource.Any(x => x.HasChanged));
            return save;
        }
    }

The checkboxes use the Event CheckBox_Checked in the following way

    private void CheckBox_Checked(object sender, RoutedEventArgs e)
    {
        CheckBox c = sender as CheckBox;
        if (!(c.DataContext is NumberOfInterest n))
            return;
        n.HasChanged = true;
        n.Prop1 = c.IsChecked.Value;
    }

and a similar one for Prop2

the problem is that HasChanged is automatically set to true if an element in my item source has any of the 2 Prop1 or Prop2 set to true by default.

I would like to find a way to trigger the CheckBox_Checked event only after the user control is in disposition of the user (i.e. the user can iteract with it and everything is loaded).

I tried to set the Loaded and Initialized to set a local boolean, but those events fire before the item source is actually set

I also tried the Mode = "OneWayToSource" in the checkbox binding, but this prevent the checkbox to be set to the proper state in the first place




Aucun commentaire:

Enregistrer un commentaire