【问题标题】:Wpf datagrid is alway validWpf 数据网格始终有效
【发布时间】:2015-06-30 14:01:43
【问题描述】:

如果我的数据网格在 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>

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

问题是,每次引发CurrentCellChangedIsValid(this.dg) 都会返回 true,即使显示红色的!

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

【问题讨论】:

    标签: c# wpf validation datagrid wpfdatagrid


    【解决方案1】:

    尝试如下更改您的 »IsValid«-Method。 这也是我的解决方案 - 有同样的问题(发现它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;
        }
    

    【讨论】:

      猜你喜欢
      • 2010-11-18
      • 2018-11-21
      • 1970-01-01
      • 2013-09-26
      • 1970-01-01
      • 2011-04-12
      • 2015-05-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多