Wpf 如何处理自定义控件上的验证

Wpf 如何处理自定义控件上的验证,wpf,mvvm,errortemplate,Wpf,Mvvm,Errortemplate,我最近写了我的第一个自定义控件,一个自动完成的文本框。它的Controltemplate由以下内容组成 <Grid > <Border/> <TextBlock x:Name="Label"/> <TextBox x:Name="TextLabel"/> </Grid> <TextBox x:Name="PART_Editor" HorizontalAlignment="Stretch" Vertic

我最近写了我的第一个自定义控件,一个自动完成的文本框。它的Controltemplate由以下内容组成

<Grid >
  <Border/>
  <TextBlock x:Name="Label"/>
  <TextBox x:Name="TextLabel"/>
</Grid>
<TextBox x:Name="PART_Editor"
    HorizontalAlignment="Stretch"
    VerticalAlignment="Center"
    Validation.ErrorTemplate="{DynamicResource ValidationErrorTemplate}"
    Style="{StaticResource TransparentTextBoxStyle}"
    Text="{Binding Path=Text, RelativeSource={RelativeSource Mode=TemplatedParent}, 
           Mode=TwoWay, ValidatesOnNotifyDataErrors=True, 
           NotifyOnValidationError=True, 
           ValidatesOnDataErrors=True, 
           UpdateSourceTrigger=PropertyChanged}" >                                                                                
</TextBox>

第一个文本块用作标签,第二个文本块显示内容。TextLabel绑定到一个对象上,我们称之为Customer。如果底层搜索没有找到Customer对象,我想显示errortemplate。当像这样定义TextLabel时

<Grid >
  <Border/>
  <TextBlock x:Name="Label"/>
  <TextBox x:Name="TextLabel"/>
</Grid>
<TextBox x:Name="PART_Editor"
    HorizontalAlignment="Stretch"
    VerticalAlignment="Center"
    Validation.ErrorTemplate="{DynamicResource ValidationErrorTemplate}"
    Style="{StaticResource TransparentTextBoxStyle}"
    Text="{Binding Path=Text, RelativeSource={RelativeSource Mode=TemplatedParent}, 
           Mode=TwoWay, ValidatesOnNotifyDataErrors=True, 
           NotifyOnValidationError=True, 
           ValidatesOnDataErrors=True, 
           UpdateSourceTrigger=PropertyChanged}" >                                                                                
</TextBox>

进行验证,并显示文本框的错误模板。不幸的是,红色边框仅在内部文本框周围,而不是整个自定义控件周围,这看起来不太好

我想知道如何实现两件事:

  • 当其中一个子验证失败时,如何触发CustomControl的ErrorTemplate
  • 我是否必须指定所有这些NotifyOnValidationerror属性,或者是否可以捕获实体级别的所有错误并显示相同的ErrorTemplate

如果您需要其他信息,请询问

将UserControl绑定到TextBox的验证。HasError,如果返回true,请添加边框。请提供更多代码