wpf - 访问验证结果

标签 wpf validation binding

嗨,我有一个带有文本框的数据网格,用于接收输入的 IP 地址。 为了验证文本框,我将其与自定义验证器绑定(bind)。

<DataGridTemplateColumn.CellTemplate>
    <DataTemplate>
        <TextBox Margin="20,10,20,10" Height="20" Width="100" HorizontalAlignment="Center" VerticalAlignment="Center" BorderBrush="{Binding Path=IPSrcValidationStatus.Color}">
             <TextBox.Text>
                  <Binding Path="IPSrc" UpdateSourceTrigger="PropertyChanged">
                      <Binding.ValidationRules>
                          <validators:IPv4ValidationRule/>
                              </Binding.ValidationRules>
                       </Binding>
                </TextBox.Text>
             </TextBox>
     </DataTemplate>
</DataGridTemplateColumn.CellTemplate>

如何从我的代码中访问 ValidationResult,或者更好的是,将其与我的 View 模型绑定(bind)?

最佳答案

验证规则纯粹发生在用户界面中。与转换失败类似,它们将您的控件设置为有错误,但不会发生从 View 到 View 模型的数据传输。

与 wpf 的常见情况一样,有多种方法可以告诉您的 View 模型 View 中存在数据错误。

您的验证规则可以获取绑定(bind)表达式并在 View 模型上设置某些属性。 Maxence 的帖子中有一些代码: Passing state of WPF ValidationRule to View Model in MVVM

我从未使用过这种方法(但看起来可行)。
我通常想了解转换失败以及任何验证规则失败。在我使用validationrule的场景中,我通常只关心有效数据是否进入 View 模型并且IsDirty==true

我经常使用的方法是在父网格中的控制树中冒泡时获取任何错误。 这里的示例有我使用的代码:

https://gallery.technet.microsoft.com/scriptcenter/WPF-Entity-Framework-MVVM-78cdc204

我设置了

NotifyOnSourceUpdated=True,
NotifyOnValidationError=True,

关于我感兴趣的所有绑定(bind)。 然后错误就会冒出来。 它们被捕获并从资源字典中的标准模板传递到 View 模型。 ConversionErrorCommand 将在转换和验证结果失败时触发。

    <Grid ...               >
                <i:Interaction.Triggers>
                    <local:RoutedEventTrigger RoutedEvent="{x:Static Validation.ErrorEvent}">
                        <e2c:EventToCommand
                                                Command="{Binding EditVM.TheEntity.ConversionErrorCommand, Mode=OneWay}"
                                                EventArgsConverter="{StaticResource BindingErrorEventArgsConverter}"
                                                PassEventArgsToCommand="True" />
                    </local:RoutedEventTrigger>
                    <local:RoutedEventTrigger RoutedEvent="{x:Static Binding.SourceUpdatedEvent}">
                        <e2c:EventToCommand
                                                Command="{Binding EditVM.TheEntity.SourceUpdatedCommand, Mode=OneWay}"
                                                EventArgsConverter="{StaticResource BindingSourcePropertyConverter}"
                                                PassEventArgsToCommand="True" />
                    </local:RoutedEventTrigger>
                </i:Interaction.Triggers>

您还需要 RoutedEventTrigger:

public class RoutedEventTrigger : EventTriggerBase<DependencyObject>
{
    RoutedEvent routedEvent;
    public RoutedEvent RoutedEvent
    {
        get
        {
            return routedEvent;
        }
        set 
        { 
            routedEvent = value;
        }
    }

    public RoutedEventTrigger()
    {
    }
    protected override void OnAttached()
    {
        Behavior behavior = base.AssociatedObject as Behavior;
        FrameworkElement associatedElement = base.AssociatedObject as FrameworkElement;
        if (behavior != null)
        {
            associatedElement = ((IAttachedObject)behavior).AssociatedObject as FrameworkElement;
        } 
        if (associatedElement == null)
        {
            throw new ArgumentException("This only works with framework elements");
        }
        if (RoutedEvent != null)
        {
            associatedElement.AddHandler(RoutedEvent, new RoutedEventHandler(this.OnRoutedEvent));
        }
    }
    void OnRoutedEvent(object sender, RoutedEventArgs args)
    {
         base.OnEvent(args);
    }
    protected override string GetEventName()
    {
        return RoutedEvent.Name;
    }
}

}

关于wpf - 访问验证结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49771072/

相关文章:

c# - 确定在 WPF 网格上单击了哪个单元格的方法?

wpf - 在 WPF 应用程序中何处放置和配置 IoC 容器?

php - HTML5 表单验证机制 : set invalidate after server side validation

binding - 如何使用格式化程序绑定(bind)属性

silverlight - 具有 CellTemplate 和绑定(bind)的自定义 DataGrid 列

wpf - WPF:CurrentDispatcher.CheckAccess和CanExecuteChanged问题

c# - wpf DataGrid - 已添加具有相同键的项目

php - 如何从 Controller 方法验证返回自定义错误消息

javascript - 验证当月内的日期

使用绑定(bind)的 WPF DataGrid 单元格背景