具有文本框和文本块的自定义控件

时间:2019-04-11 22:07:24

标签: xaml uwp custom-controls uwp-xaml

我想构建一个验证文本框,该文本框是包装在TextBox中的普通UWP StackPanel,该文本框还包含一个TextBlock。目的是当出现验证错误时,可以在文本框下方显示验证消息。

我知道我可以通过创建自定义控件来做到这一点,但这将要求我实现所需的所有属性并创建一堆依赖项属性,等等。

我希望有一种更简单的方法,我可以完全派生文本框,但是覆盖它的显示模板并在其下面添加标签。

1 个答案:

答案 0 :(得分:-1)

使用内置的基于IDataErrorInfo的验证机制并为TextBox的Validation.ErrorTemplate定义控制模板,可以在XAML中获得大部分功能。 this link:

上有一篇不错的文章

下面链接中文章的XAML如下,还请查看有关WPF内置验证here的讨论。

<Style TargetType="{x:Type Label}">
    <Setter Property="Margin" Value="5,0,5,0" />
    <Setter Property="HorizontalAlignment" Value="Left" />
</Style>
<Style TargetType="{x:Type TextBox}">
    <Setter Property="VerticalAlignment" Value="Center" />
    <Setter Property="Margin" Value="0,2,40,2" />
    <Setter Property="Validation.ErrorTemplate">
        <Setter.Value>
            <ControlTemplate>
                <DockPanel LastChildFill="true">
                    <Border Background="OrangeRed" DockPanel.Dock="right" Margin="5,0,0,0" 
                            Width="20" Height="20" CornerRadius="5"
                            ToolTip="{Binding ElementName=customAdorner, 
                                      Path=AdornedElement.(Validation.Errors)[0].ErrorContent}">
                    <TextBlock Text="!" VerticalAlignment="center" HorizontalAlignment="center" 
                               FontWeight="Bold" Foreground="white" />
                    </Border>
                    <AdornedElementPlaceholder Name="customAdorner" VerticalAlignment="Center" >
                        <Border BorderBrush="red" BorderThickness="1" />
                    </AdornedElementPlaceholder>
                </DockPanel>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>