简体   繁体   中英

WPF validation custom trigger

I have couple of bound TextBoxes with validation enabled.

  <TextBox Text="{Binding Name, ValidatesOnDataErrors=True" />
  <TextBox Text="{Binding Password, ValidatesOnDataErrors=True" />
  <Button Command="{Binding OkCommand}"/>

When view is opened i have these textboxes invalid by default because I have NotEmpty vlaidation on them.

I want validation to happen only at last moment, when i click Ok. How can I trigger validation from code (Button`s Command)?

You can trigger the validation explicitly by setting the UpdateSourceTrigger to Explicit for your binding like this -

<TextBox x:Name="textBox1"
         Text="{Binding Name, ValidatesOnDataErrors=True, 
                              UpdateSourceTrigger=Explicit}"/>
<TextBox x:Name="textBox2"
         Text="{Binding Password, ValidatesOnDataErrors=True, 
                                  UpdateSourceTrigger=Explicit}" />
<Button Click="Button_Click"/>

And in handler you have to explicitly update the source like this -

private void Button_Click(object sender, RoutedEventArgs e)
{
    textBox1.GetBindingExpression(TextBox.TextProperty).UpdateSource();
    textBox2.GetBindingExpression(TextBox.TextProperty).UpdateSource();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM