WPF Validation Control Template overlapping

后端 未结 2 961
傲寒
傲寒 2021-01-05 23:12

I\'ve got a user control with a control template to show validation errors, validation template:



        
相关标签:
2条回答
  • 2021-01-05 23:34

    I'd say this is because your error message is on the AdornerLayer, which doesn't participate in the same layout as your control. MSDN says "rendering of an adorner is independent from rendering of the UIElement that the adorner is bound to." and that is why the message is just put on top of everything.

    You could put the error text into the original template, hide it based on Validation.HasError and include it in the layout process that way.

    But changing the layout of the control might not be the best way to go if a validation error occurs. You might consider providing additional information in a ToolTip.

    0 讨论(0)
  • 2021-01-05 23:51

    Alternately, instead of using ControlTemplate, you could put the error message TextBlock beside the TextBox, and set its Text property binding the TextBox's ErrorContent.

    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <TextBox x:Name="txtName" Grid.Row="0">
            <TextBox.Text>
                <Binding Path="Name" NotifyOnValidationError="True" ValidatesOnExceptions="True" UpdateSourceTrigger="PropertyChanged">
                    <Binding.ValidationRules>
                        <common:RequiredFieldValidationRule/>
                    </Binding.ValidationRules>
                </Binding>
            </TextBox.Text>
        </TextBox>
        <TextBlock Grid.Row="1" Text="{Binding ElementName=txtName,Path=(Validation.Errors)[0].ErrorContent}"
                   Visibility="{Binding ElementName=txtName,Path=Validation.HasError,Converter=...}" />
    </Grid>
    
    0 讨论(0)
提交回复
热议问题