关于这个主题有一篇很好的 MSDN 杂志文章,具有模型-视图-视图模型设计模式的 WPF 应用程序:http: //msdn.microsoft.com/en-us/magazine/dd419663.aspx
根据这篇文章,在数据模型和存储库部分 ( http://msdn.microsoft.com/en-us/magazine/dd419663.aspx#id0090102 ),您会发现一个简单的实现。Customer 是实体类,ViewModel 从实体获取错误指示符。
您可以使用 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>