从代码访问WPF控件验证规则

Ale*_*x F 16 validation wpf binding

XAML:

  <TextBox Name="textboxMin">
      <TextBox.Text>
          <Binding Path="Max">
              <Binding.ValidationRules>
                  <local:IntValidator/>
              </Binding.ValidationRules>
          </Binding>
      </TextBox.Text>
  </TextBox>

码:

void buttonOK_Click(object sender, RoutedEventArgs e)
{
    // I need to know here whether textboxMin validation is OK
    // textboxMin. ???

    // I need to write something like:
    // if ( textboxMin.Validation.HasErrors )
    //     return;
}

如果至少有一个对话框控件没有通过验证 - 在XAML中,使用绑定,那么知道如何禁用OK按钮也会很好.有了这种方式,我不需要检查代码中的验证状态.

Fre*_*lad 26

Validation.HasError是一个附加属性,因此您可以像这样检查textboxMin

void buttonOK_Click(object sender, RoutedEventArgs e)
{
    if (Validation.GetHasError(textboxMin) == true)
         return;
}
Run Code Online (Sandbox Code Playgroud)

要在代码中运行TextProperty的所有ValidationRules,您可以获取BindingExpression并调用UpdateSource

BindingExpression be = textboxMin.GetBindingExpression(TextBox.TextProperty);
be.UpdateSource();
Run Code Online (Sandbox Code Playgroud)

更新

如果发生任何验证,将需要一些步骤来实现绑定以禁用按钮.

首先,确保所有绑定都添加NotifyOnValidationError ="True".例

<TextBox Name="textboxMin">
    <TextBox.Text>
        <Binding Path="Max" NotifyOnValidationError="True">
            <Binding.ValidationRules>
                <local:IntValidator/>
            </Binding.ValidationRules>
        </Binding>
    </TextBox.Text>
</TextBox>
Run Code Online (Sandbox Code Playgroud)

然后我们将一个EventHandler连接到Window中的Validation.Error事件.

<Window ...
        Validation.Error="Window_Error">
Run Code Online (Sandbox Code Playgroud)

在后面的代码中,我们在observablecollection中添加和删除验证错误,因为它们来来去去

public ObservableCollection<ValidationError> ValidationErrors { get; private set; } 
private void Window_Error(object sender, ValidationErrorEventArgs e)
{
    if (e.Action == ValidationErrorEventAction.Added)
    {
        ValidationErrors.Add(e.Error);
    }
    else
    {
        ValidationErrors.Remove(e.Error);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后我们可以像这样将Button的IsEnabled绑定到ValidationErrors.Count

<Button ...>
    <Button.Style>
        <Style TargetType="Button">
            <Setter Property="IsEnabled" Value="False"/>
            <Style.Triggers>
                <DataTrigger Binding="{Binding ValidationErrors.Count}" Value="0">
                    <Setter Property="IsEnabled" Value="True"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Button.Style>
</Button>
Run Code Online (Sandbox Code Playgroud)


Tal*_*ner 6

在获得规则之前,你需要先获得Binding

    Binding b=  BindingOperations.GetBinding(textboxMin,TextBox.TextProperty);
    b.ValidationRules
Run Code Online (Sandbox Code Playgroud)

否则你可以使用BindingExpression并检查HasError属性

 BindingExpression be1 = BindingOperations.GetBindingExpression (textboxMin,TextBox.TextProperty);

be1.HasError
Run Code Online (Sandbox Code Playgroud)