监视所有验证事件 [英] Monitor for all validation events

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

问题描述

非常容易,以检查某些容器或其子容器是否存在验证错误.可以用来禁用保存按钮.

It's quite easy to check if certain container or its children have validation errors. This can be used to disable Save button.

我可以使用计时器

public SomeUserControl()
{
    InitializeComponent();
    var timer = new DispatcherTimer
    {
        Interval = TimeSpan.FromMilliseconds(100),
        IsEnabled = true
    };
    Loaded += (s, e) => buttonSave.IsEnabled = IsValid(grid);
    Unloaded += (s, e) => timer.Stop();
}

轮询和禁用按钮.

<!-- container with lots of controls, bindings and validations -->
<Grid x:Name="grid">
   ...
</Grid>

<!-- save button -->
<Button x:Name="buttonSave" ... />

有更好的方法吗?理想情况下,我想要一个事件.不幸的是,我发现的唯一事件验证.Error 事件,仅可用于具有绑定本身的元素.遍历子元素并订阅(更不用说我必须添加新的子元素了)比投票更糟糕.

Is there a better way? Ideally I want an event. Unfortunately the only event I've found, Validation.Error event, can only be used on the element with bindings itself. Going through children elements and subscribing (not mentioning what I have to deal with adding new children) feels way worser than polling.

有想法吗?

推荐答案

我通常的处理方式如下所示:

The way I usually handle this is illustrated here:

https://social.technet.microsoft.com/wiki/contents/articles/28597.aspx

errorevent将冒泡到容器中,您可以处理它,使用行为或命令将其传递给视图模型.

The errorevent will bubble to a container and you can handle that, use a behavior or command to pass it to the viewmodel.

赞:

<ControlTemplate x:Key="AddingTriggers" TargetType="ContentControl">
    <ControlTemplate.Resources>
        <Style TargetType="{x:Type TextBox}" BasedOn="{StaticResource ErrorToolTip}">
            <Setter Property="HorizontalAlignment" Value="Left"/>
        </Style>

    </ControlTemplate.Resources>
    <StackPanel>
        <i:Interaction.Triggers>
            <local:RoutedEventTrigger RoutedEvent="{x:Static Validation.ErrorEvent}">
                <e2c:EventToCommand   Command="{Binding ConversionErrorCommand, Mode=OneWay}"
                                        EventArgsConverter="{StaticResource BindingErrorEventArgsConverter}"
                                        PassEventArgsToCommand="True" />
            </local:RoutedEventTrigger>
        </i:Interaction.Triggers>
        <TextBlock Text="This would be some sort of a common header" Foreground="LightBlue" HorizontalAlignment="Right"/>
        <ContentPresenter/> <!-- This is how you can have variable content "within" the control -->
        <TextBlock Text="This would some sort of a common footer" Foreground="LightBlue"  HorizontalAlignment="Right"/>
    </StackPanel>
</ControlTemplate>

在任何绑定上都需要NotifyOnValidationError = True.

You need NotifyOnValidationError=True on any bindings.

这篇关于监视所有验证事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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