Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Wpf 如何跳过已禁用元素的验证?_Wpf_Validation_Data Binding - Fatal编程技术网

Wpf 如何跳过已禁用元素的验证?

Wpf 如何跳过已禁用元素的验证?,wpf,validation,data-binding,Wpf,Validation,Data Binding,我是WPF的新手。在我们当前的项目中,我们为所有需要验证的数据输入字段添加了验证规则。我们还复制了递归循环所有绑定及其验证规则的代码(也发布在stackoverflow的其他地方),以便在保存数据之前知道所有数据是否有效 这是我们的代码,我认为是解决我们问题的地方: Public Function ValidateBindings(ByVal parent As DependencyObject) As Boolean Dim valid As Boolean = True Dim lo

我是WPF的新手。在我们当前的项目中,我们为所有需要验证的数据输入字段添加了验证规则。我们还复制了递归循环所有绑定及其验证规则的代码(也发布在stackoverflow的其他地方),以便在保存数据之前知道所有数据是否有效

这是我们的代码,我认为是解决我们问题的地方:

Public Function ValidateBindings(ByVal parent As DependencyObject) As Boolean
  Dim valid As Boolean = True
  Dim localValues As LocalValueEnumerator = parent.GetLocalValueEnumerator

  While localValues.MoveNext
   Dim entry As LocalValueEntry = localValues.Current
   If BindingOperations.IsDataBound(parent, entry.Property) Then
    Dim binding As Binding = BindingOperations.GetBinding(parent, entry.Property)
    For Each rule In binding.ValidationRules
     Dim result As ValidationResult = rule.Validate(parent.GetValue(entry.Property), Nothing)
     If Not result.IsValid Then
      Dim expression As BindingExpression = BindingOperations.GetBindingExpression(parent, entry.Property)
      Validation.MarkInvalid(expression, New ValidationError(rule, expression, result.ErrorContent, Nothing))
      valid = False
     End If
    Next
   End If
  End While

  For i As Integer = 0 To VisualTreeHelper.GetChildrenCount(parent) - 1
   Dim child As DependencyObject = VisualTreeHelper.GetChild(parent, i)

   If Not ValidateBindings(child) Then
    valid = False
   End If
  Next

  Return valid
 End Function
我试图了解如何在父级
IsEnableProperty
依赖项属性上使用
GetValue()
,但迄今为止我的尝试都失败了。 有谁能帮我解决这个问题的正确思路吗

或者,当字段被禁用时,我一直在考虑将验证错误绑定到“忽略任何内容”规则,但这对我来说似乎更麻烦

我试图通过XAML中的绑定来设置
绑定.NotifyOnValidationError
,以便为元素的
IsEnabled
NotifyOnValidationError
绑定到相同的值,但我无法这样做,因为它不是DependencyProperty

我尝试的另一件事是在validation类中添加一个属性
ElementIsEnabled
,这样在XAML中就可以做到:


    <Binding.ValidationRules>
        <local:MustContainInteger ElementIsEnabled="{Binding SameBindingAsIsEnabled}" />
     </Binding.ValidationRules>

但这也失败了,因为
ElementIsEnabled
不是DependencyObject上的DependencyProperty


无论如何,在此方面的任何帮助都将不胜感激。

在.NET 4中,您现在可以通过以下方式获得对ValidationRule中元素的引用:


当然,这允许您在
验证中检查
元素。IsEnabled

public class MustContainInteger : ValidationRule
{
    public UIElement Element { get; set; }

    // ...
}