在WPF中对绑定控件进行强制验证 [英] Force validation on bound controls in WPF

查看:92
本文介绍了在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.

谢谢。

推荐答案

我们的应用程序中也存在此问题。验证仅在绑定更新时触发,因此您必须手动更新它们。我们在窗口的已加载事件:

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();
}

这将显示错误模板(红色轮廓),并设置<我们拥有的href = http://msdn.microsoft.com/zh-cn/library/system.windows.controls.validation.haserror.aspx rel = noreferrer> 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天全站免登陆