0

I would like to disable a button if my datagrid have error in WPF

This is my codebehind

   private bool IsValid(DependencyObject obj)
    {
        return !Validation.GetHasError(obj) &&
        LogicalTreeHelper.GetChildren(obj)
        .OfType<DependencyObject>()
        .All(IsValid);
    }

    private void dg_BeginningEdit(object sender, DataGridBeginningEditEventArgs e)
    {
        var mvm = SimpleIoc.Default.GetInstance<MainViewModel>();
        mvm.ReferenceVM.SaveButtonIsEnabled = false;
    }


    private void dg_CurrentCellChanged(object sender, EventArgs e)
    {
        var mvm = SimpleIoc.Default.GetInstance<MainViewModel>();

        if (IsValid(this.dg))
        {
            mvm.ReferenceVM.SaveButtonIsEnabled = true;
        }
        else
            mvm.ReferenceVM.SaveButtonIsEnabled = false;
    }

Isvalid function comes frome here : Detecting WPF Validation Errors

In my datagrid, I use rowValidationRule

        <DataGrid.RowValidationRules>
            <local:MyRowValidation CurrentCollection="{StaticResource CurrentDatas}" ValidationStep="CommittedValue" ValidatesOnTargetUpdated="True"/>
        </DataGrid.RowValidationRules>

The validation works fine (I have a red ! when a cells is bad filled)

The problem is, each time CurrentCellChanged is raised, IsValid(this.dg) return true, even when the red ! is displayed.

So the question is :
- Why IsValid always return true ?
- Where is the good location to check if the datagrid is correct ?

Community
  • 1
  • 1
Titouan56
  • 6,932
  • 11
  • 37
  • 61

1 Answers1

0

Try to change your »IsValid«-Method as follows. That was also the solution for me - had the same problem (found it here)

    private bool IsValid(DependencyObject parent)
    {
        if (Validation.GetHasError(parent))
            return false;

        // Validate all the bindings on the children
        for (int i = 0; i != VisualTreeHelper.GetChildrenCount(parent); ++i)
        {
            DependencyObject child = VisualTreeHelper.GetChild(parent, i);
            if (!IsValid(child)) { return false; }
        }

        return true;
    }
Community
  • 1
  • 1