嗨,我有一个带有文本框的数据网格,用于接收输入的 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/