【问题标题】:WPF Validation Control Template overlappingWPF 验证控制模板重叠
【发布时间】:2011-06-29 05:25:50
【问题描述】:

我有一个带有控件模板的用户控件来显示验证错误,验证模板:

<ControlTemplate x:Key="TextBoxPropertyValidationTemplate">
        <StackPanel>
            <Border BorderBrush="Red" BorderThickness="1">
                <AdornedElementPlaceholder x:Name="MyAdorner" />
            </Border>

            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="Auto" />
                    <ColumnDefinition Width="*" />
                </Grid.ColumnDefinitions>
                <Image Grid.Column="0" MaxHeight="16" MaxWidth="16"
                       Source="{Binding Source={StaticResource ValidationIcon}, Converter={StaticResource UriConverter}}" 
                       Margin="1" RenderOptions.BitmapScalingMode="HighQuality"
                       VerticalAlignment="Center" HorizontalAlignment="Center" />
                <TextBlock VerticalAlignment="Center" HorizontalAlignment="Left"
                           Text="{Binding ElementName=MyAdorner, Path=AdornedElement.(Validation.Errors)[0].ErrorContent}"
                           TextWrapping="Wrap" Grid.Column="1" FontSize="10" Foreground="Red" />
            </Grid>

        </StackPanel>
    </ControlTemplate>

而且我似乎无法解决一个相当烦人的问题,如下所示:

我一直在尝试使用用户控件和模板上的边距以及一些 Height=Auto 等,但所有这些都没有真正的帮助。有什么想法吗?

如果这有助于主用户控件(嵌套有验证的控件)位于带有 AdornerDecorator 的 TabItem 中。

任何帮助表示赞赏。

【问题讨论】:

  • 你希望这个是什么样子的?我看到了重叠,但我不清楚你希望它如何表现。

标签: wpf validation controltemplate adorner


【解决方案1】:

我会说这是因为您的错误消息在AdornerLayer 上,它与您的控件不参与相同的布局。 MSDN says "装饰器的渲染独立于装饰器绑定到的 UIElement 的渲染。"这就是为什么信息只是放在一切之上的原因。

您可以将错误文本放入原始模板中,根据Validation.HasError 将其隐藏,然后将其包含在布局过程中。

但是如果发生验证错误,更改控件的布局可能不是最好的方法。您可以考虑在工具提示中提供其他信息。

【讨论】:

  • 好答案,很公平...我不希望我的布局跳来跳去,所以它看起来像工具提示。谢谢
【解决方案2】:

或者,您可以不使用 ControlTemplate,而是将错误消息 TextBlock 放在 TextBox 旁边,并将其 Text 属性设置为绑定 TextBox 的 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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 2016-02-05
    • 2014-08-22
    • 2012-08-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多