Wpf datagrid总是有效的

时间:2015-06-30 14:01:43

标签: c# wpf validation datagrid wpfdatagrid

如果我的数据网格在WPF中有错误,我想禁用一个按钮

这是我的代码隐藏

   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函数来自:Detecting WPF Validation Errors

在我的数据网格中,我使用rowValidationRule

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

验证工作正常(当单元格填充不好时,我有一个红色的!

问题是,每次引发CurrentCellChanged时,IsValid(this.dg)都会返回true,即使显示红色!也是如此。

所以问题是:
   - 为什么IsValid总是返回true?    - 检查数据网格是否正确的好位置在哪里?

1 个答案:

答案 0 :(得分: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;
    }