TextBox的Validation.ErrorTemplate对齐TextBox
时间: 2024-01-21 09:17:14 浏览: 199
要对齐Validation.ErrorTemplate和TextBox,可以使用Grid和SharedSizeGroup。例如:
```xml
<Grid>
<Grid.Resources>
<Style TargetType="{x:Type TextBox}">
<Setter Property="Margin" Value="5"/>
<Setter Property="Height" Value="30"/>
<Setter Property="HorizontalAlignment" Value="Stretch"/>
<Setter Property="VerticalAlignment" Value="Center"/>
</Style>
<Style x:Key="ErrorTemplate" TargetType="{x:Type Control}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<StackPanel Orientation="Horizontal" Grid.IsSharedSizeScope="True">
<Image Source="error.png" Width="16" Height="16" Margin="0,0,5,0"/>
<TextBlock Text="{Binding}" Foreground="Red" Margin="0,0,5,0" VerticalAlignment="Center"/>
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Grid.Resources>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" SharedSizeGroup="Label"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Text="Name:" Grid.Column="0" VerticalAlignment="Center"/>
<TextBox Text="{Binding Name, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}" Grid.Column="1">
<Validation.ErrorTemplate>
<ControlTemplate>
<Border BorderBrush="Red" BorderThickness="1">
<AdornedElementPlaceholder/>
</Border>
</ControlTemplate>
</Validation.ErrorTemplate>
</TextBox>
<TextBlock Text="Age:" Grid.Column="0" VerticalAlignment="Center"/>
<TextBox Text="{Binding Age, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}" Grid.Column="1">
<Validation.ErrorTemplate>
<ControlTemplate>
<Border BorderBrush="Red" BorderThickness="1">
<AdornedElementPlaceholder>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" SharedSizeGroup="Label"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Border BorderBrush="Red" BorderThickness="1" Grid.Column="1">
<StackPanel Orientation="Horizontal">
<Image Source="error.png" Width="16" Height="16" Margin="0,0,5,0"/>
<TextBlock Text="{Binding}" Foreground="Red" Margin="0,0,5,0" VerticalAlignment="Center"/>
</StackPanel>
</Border>
</Grid>
</AdornedElementPlaceholder>
</Border>
</ControlTemplate>
</Validation.ErrorTemplate>
</TextBox>
</Grid>
```
在上面的示例中,我们将TextBox和ErrorTemplate放在一个Grid中,并使用SharedSizeGroup将它们对齐。我们还为TextBox和ErrorTemplate创建了两个Style,以便可以重用它们。对于ErrorTemplate,我们使用了一个StackPanel来放置错误图像和文本,然后将它们放在一个Grid中,这样它们就可以与TextBox对齐。
阅读全文