我有一个UserControl ,里面有一个TextBox。当TextBox 级别出现错误时,我想在UserControl 级别显示一条消息。并在 TexBox 级别显示错误消息。
我们没有使用 MVVM。这是一个可重复使用的控件。然而,这是一个可重用的控件,使用它的人很可能会自己使用 MVVM。
他们会像这样将它添加到他们的视图中:
<myUserControlNamespace:MyUserControl x:Name="control1" Value="{Binding Value}" OtherProperty="{Binding OtherValue}" />
我的控件里面有一个 TexBox,它绑定到“值”。它的值是一个 Double,所以当用户在 TexBox 上输入一个字母时会抛出一个错误。我的 TextBox 绑定类似于:
<TextBox Grid.Column="1" x:Name="valueTextBox" Style="{DynamicResource ValidatingTextBox}"
Validation.ValidationAdornerSite="{Binding ElementName=valueTextBox}"
Validation.ValidationAdornerSiteFor="{Binding}" >
<TextBox.Text>
<MultiBinding Converter="{StaticResource MyConverter}"Mode="TwoWay" >
<Binding RelativeSource="{RelativeSource AncestorType={x:Type unitConversion:UnitConversionControl}}" UpdateSourceTrigger="PropertyChanged" Path="Value" Mode="TwoWay" />
<Binding RelativeSource="{RelativeSource AncestorType={x:Type unitConversion:UnitConversionControl}}" Path="OtherProperty"/>
</MultiBinding>
</TextBox.Text>
Style ValidatingTexBox 有这样的东西:
<Style x:Key="ValidatingTextBox" TargetType="{x:Type TextBox}">
<Setter Property="Validation.ErrorTemplate">
<Setter.Value>
<ControlTemplate>
<StackPanel Orientation="Vertical">
<AdornedElementPlaceholder />
<TextBlock Foreground="Red" Text="{Binding ErrorContent}" Height="16" Margin="2"/>
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="True">
<Setter Property="Background"
Value="LightPink" />
<Setter Property="Foreground"
Value="Black" />
<Setter Property="Margin" Value="5,5,5,28"/>
<Setter Property="ToolTip"
Value="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}" />
</Trigger>
</Style.Triggers>
我希望我的客户的用户以与我使用 TextBox 类似的方式使用我的控件。设置 MyUserControl 样式,并使用 Validation.ErrorTemplate 来显示错误。
当 TexBox 中出现错误时,我希望我的控件也有错误,因此使用我的控件的人可以处理它,例如使用 Validation.ErrorTemplate。
有没有办法“级联”错误?
我读了这个SO 问题,他正在使用INotifyDataErrorInfo,我不能,因为我使用的是 .Net 4.0,但我读到我可以改用 IDataErrorInfo。我必须让我的控件实现 IDataErrorInfo。这个对吗?
让我知道是否需要添加更多细节。