如果我的域对象实现IDataErrorInfo的,而且我在使用M-V-VM,我怎么传播通过视图模型误差进入查看?如果我是直接绑定到模型中,我将设置我的绑定“ValidateOnExceptons”和“ValidateOnErrors”属性设置为true。但我的视图模型不实现IDataErrorInfo的。只有我的模型。我该怎么办?

<强>澄清 我处理的,在领域对象实现IDataErrorInfo的现有代码库。我不能只实现IDataErrorInfo的在我的视图模型。

有帮助吗?

解决方案

您可以在VM和路由呼叫到虚拟机的相应的域对象另外实现IDataErrorInfo的。我认为这是在不直接暴露域对象的视图的唯一途径。

其他提示

如果使用的是M-V-VM,视图模型应该定义IDataErrorInfo的界面,而不是模型。

您可以说,IDataErrorInfo的接口只是一种观点,并没有在模型中属于,但是这是一个风格的问题。

具有视图模型实现IDataErrorInfo的接口和传播从模型的误差将是最简单的答案。

有关于这个主题的一个很好的MSDN杂志文章,WPF应用程序与模型 - 视图 - 视图模型设计模式:的 http://msdn.microsoft.com/en-us/magazine/dd419663.aspx

根据这篇文章,在数据模型和信息库段( http://msdn.microsoft.com/en-us/magazine/dd419663.aspx#id0090102 ),你会发现一个简单的实现。客户是实体类和视图模型从实体获得误差指标。

您可以使用ValidationsRule来检查数据的有效性:

<TextBox x:Name="title" VerticalAlignment="Top" TextWrapping="Wrap" Grid.Column="1" MinWidth="20">
  <TextBox.Text>
    <Binding Path="Title" UpdateSourceTrigger="LostFocus">
      <Binding.ValidationRules>
        <Validators:StringRangeValidationRule MinimumLength="1" MaximumLength="30" 
                                            ErrorMessage="Address is required and must be less than 30 letters." />
      </Binding.ValidationRules>
    </Binding>
  </TextBox.Text>
</TextBox>

这是验证定型的示例:

<Application.Resources>
  <Style TargetType="{x:Type TextBox}">
  <Setter Property="Validation.ErrorTemplate">
    <Setter.Value>
      <ControlTemplate>
        <DockPanel LastChildFill="True">
          <Image Source="/Images/error.png" Width="25" Height="25" ToolTip="{Binding ElementName=MyAdorner, Path=AdornedElement.(Validation.Errors)[0].ErrorContent}" />
          <TextBlock DockPanel.Dock="Right"
              Foreground="Orange"
              Margin="5" 
              FontSize="12pt"
              Text="{Binding ElementName=MyAdorner, Path=AdornedElement.(Validation.Errors)[0].ErrorContent}">
          </TextBlock>

          <Border BorderBrush="Red" BorderThickness="3">
          <AdornedElementPlaceholder Name="MyAdorner" />
        </Border>
      </DockPanel>
    </ControlTemplate>
  </Setter.Value>
</Setter>
<Style.Triggers>
  <Trigger Property="Validation.HasError" Value="true">
    <Setter Property="ToolTip"
        Value="{Binding RelativeSource={RelativeSource Self}, 
        Path=(Validation.Errors)[0].ErrorContent}"/>
  </Trigger>
</Style.Triggers>

,点击

scroll top