【问题标题】:ErrorTemplate for PasswordBox with AttachedProperty带有 AttachedProperty 的 PasswordBox 的 ErrorTemplate
【发布时间】:2011-10-13 12:57:25
【问题描述】:

我知道 wpf 中的密码框无法使用 Validation.ErrorTemplate,无论如何我必须向用户显示出问题了。

我的密码箱有这样的绑定

 <PasswordBox Name="Password" local:PasswordHelper.Text="{Binding PasswordProp, Mode=TwoWay}" />

如果有问题,是否可以获得与此密码框的默认错误模板(红色边框)相同的样式?

这是我用于其他控件的 ErrorTemplate

<Style x:Key="baseControlStyle">
    <Setter Property="Control.FontFamily" Value="Verdana" />
    <Setter Property="Control.FontSize" Value="12" />
    <Setter Property="ToolTipService.ShowOnDisabled" Value="True" />

    <Setter Property="Validation.ErrorTemplate" >
        <Setter.Value>
            <ControlTemplate>
                <DockPanel LastChildFill="True">
                    <Image x:Name="Bild" 
                           DockPanel.Dock="Right" 
                           Source="../Resources/Nein.ico" 
                           Margin="-5 0 0 0" 
                           MaxHeight="16" 
                           MaxWidth="16" 
                           VerticalAlignment="Center" 
                           ToolTip="{Binding ElementName=myControl, Path=AdornedElement.(Validation.Errors)[0].ErrorContent}">
                    </Image>
                    <Border BorderBrush="Red" BorderThickness="1" CornerRadius="2">
                        <AdornedElementPlaceholder x:Name="myControl" />
                    </Border>
                </DockPanel>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
    <Style.Triggers>
        <Trigger Property="Validation.HasError" Value="true">
            <Setter Property="Control.ToolTip" Value="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}"/>
        </Trigger>
    </Style.Triggers>
</Style>

谢谢

【问题讨论】:

    标签: wpf validation error-handling passwordbox


    【解决方案1】:

    一种解决方案是在PasswordBox 下放置一个实际的TextBox,并将Text 属性也绑定到PasswordProp,并为TextBox 提供ErrorTemplate:

    <Grid>
        <TextBox Template="{x:Null}" Style="{StaticResource baseControlStyle}" Text="{Binding PasswordProp, Mode=TwoWay}" />    
        <PasswordBox Name="Password" local:PasswordHelper.Text="{Binding PasswordProp, Mode=TwoWay}" />
    </Grid>
    

    由于 ErrorTemplate 的控件将放置在装饰层上,因此您的错误模板将显示在 PasswordBox 事件之上,尽管 TextBox 位于 PasswordBox 下方。

    另外请注意,我已将TextBox 控制模板设置为null。由于它不应该是可见的,因此不需要渲染。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-08-19
      • 2012-04-12
      • 2018-05-04
      • 2013-05-26
      • 2016-12-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多