我有 UserControl ,里面有 TextBox 。当TextBox级别错误时,我想在 UserControl级别显示消息。并在TexBox级别显示错误消息。
我们没有使用MVVM。这是一个可重用的控件。 但是,这是一个可重用的控件,使用它的人可能会自己使用MVVM。
他们会将它添加到他们的View中:
<myUserControlNamespace:MyUserControl x:Name="control1" Value="{Binding Value}" OtherProperty="{Binding OtherValue}" />
我的Control里面有一个TexBox,绑定到“Value”。值为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出现错误时,我希望我的Control也有错误,因此使用我的控件的人可以处理它,例如使用Validation.ErrorTemplate。
有没有办法“级联”错误?
我读了这个SO question,他正在使用 INotifyDataErrorInfo ,我不能因为我使用.Net 4.0,但我读到我可以改为使用IDataErrorInfo。我必须使我的控件实现IDataErrorInfo。这是对的吗?
如果我需要添加更多细节,请告诉我。