强制验证 WPF 中的绑定控件 [英] Force validation on bound controls in WPF

查看:23
本文介绍了强制验证 WPF 中的绑定控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 WPF 对话框,上面有几个文本框.文本框绑定到我的业务对象并附加了 WPF 验证规则.

I have a WPF dialog with a couple of textboxes on it. Textboxes are bound to my business object and have WPF validation rules attached.

问题是用户可以完美地单击确定"按钮并关闭对话框,而无需将数据实际输入到文本框中.验证规则永远不会触发,因为用户甚至没有尝试将信息输入到文本框中.

The problem is that user can perfectly click 'OK' button and close the dialog, without actually entering the data into textboxes. Validation rules never fire, since user didn't even attempt entering the information into textboxes.

是否可以强制验证检查并确定某些验证规则是否被破坏?

Is it possible to force validation checks and determine if some validation rules are broken?

我可以在用户尝试关闭对话框时执行此操作,并在违反任何验证规则的情况下禁止他执行此操作.

I would be able to do it when user tries to close the dialog and prohibit him from doing it if any validation rules are broken.

谢谢.

推荐答案

我们的应用程序中也有这个问题.验证仅在绑定更新时触发,因此您必须手动更新它们.我们在 Window 的 Loaded 事件:

We have this issue in our application as well. The validation only fires when bindings update, so you have to update them by hand. We do this in the Window's Loaded event:

public void Window_Loaded(object sender, RoutedEventArgs e)
{
    // we manually fire the bindings so we get the validation initially
    txtName.GetBindingExpression(TextBox.TextProperty).UpdateSource();
    txtCode.GetBindingExpression(TextBox.TextProperty).UpdateSource();
}

这将使错误模板(红色轮廓)出现,并设置Validation.HasError 属性,我们触发了确定按钮禁用:

This will make the error template (red outline) appear, and set the Validation.HasError property, which we have triggering the OK button to disable:

<Button x:Name="btnOK" Content="OK" IsDefault="True" Click="btnOK_Click">
    <Button.Style>
        <Style TargetType="{x:Type Button}">
            <Setter Property="IsEnabled" Value="false" />
            <Style.Triggers>
                <!-- Require the controls to be valid in order to press OK -->
                <MultiDataTrigger>
                    <MultiDataTrigger.Conditions>
                        <Condition Binding="{Binding ElementName=txtName, Path=(Validation.HasError)}" Value="false" />
                        <Condition Binding="{Binding ElementName=txtCode, Path=(Validation.HasError)}" Value="false" />
                    </MultiDataTrigger.Conditions>
                    <Setter Property="IsEnabled" Value="true" />
                </MultiDataTrigger>
            </Style.Triggers>
        </Style>
    </Button.Style>
</Button>

这篇关于强制验证 WPF 中的绑定控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆