我在ControlTemplate
属性中有一个Page.Resources
:
<ControlTemplate x:Key="validationErrorTemplate">
<DockPanel>
<StackPanel Orientation="Horizontal" DockPanel.Dock="Top">
<Grid Width="12" Height="12">
<Ellipse Width="12" Height="12"
Fill="Red" HorizontalAlignment="Center"
VerticalAlignment="Center"/>
<TextBlock Foreground="White" FontWeight="Bold"
FontSize="8" HorizontalAlignment="Center"
VerticalAlignment="Center" TextAlignment="Center"
ToolTip="{Binding ElementName=ErrorAdorner, Path=AdornedElement.(Validation.Errors)[0].ErrorContent}">X</TextBlock>
</Grid>
<TextBlock Foreground="Red" FontWeight="12" Margin="2,0,0,0"
Text="{Binding ElementName=ErrorAdorner, Path=AdornedElement.(Validation.Errors)[0].ErrorContent}"/>
</StackPanel>
<AdornedElementPlaceholder x:Name="ErrorAdorner"/>
</DockPanel>
</ControlTemplate>
我用于一个TextBox
控件的模板:
<TextBox Name="txtUserName"
Grid.Row="2" Grid.Column="2"
Margin="0,5,0,5"
VerticalContentAlignment="Center"
Validation.ErrorTemplate="{StaticResource validationErrorTemplate}">
<TextBox.Text>
<Binding Path="Name" Mode="TwoWay"
UpdateSourceTrigger="LostFocus">
<Binding.ValidationRules>
<validators:UserNameValidator/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
我还写了一个自定义验证器:
using System.Windows.Controls;
namespace PolovniDijelovi.Validators.LogIn
{
class UserNameValidator : ValidationRule
{
public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
{
if (value.ToString() == string.Empty)
{
return new ValidationResult(false, "Korisničko ime ne može biti prazno.");
}
else if (value.ToString().Length > 12)
{
return new ValidationResult(false, "Korisničko ime ne može sadržati više od 12 znakova.");
}
return ValidationResult.ValidResult;
}
}
}
毕竟它不起作用。当我在UserNameValidator
类中设置断点时,它永远不会达到该断点。
我是初学者,但我无法找到解决方案。 请帮忙。
答案 0 :(得分:0)
尝试以下方式并扩展您的style
&#34;视觉效果&#34;你喜欢的方式。
有一个包含validation template
和<TextBox Name="textBox1"
Validation.ErrorTemplate="{StaticResource validationTemplate}"
Style="{StaticResource textBoxInError}"
Grid.Row="1" Grid.Column="1" Margin="2">
<TextBox.Text>
<Binding Path="Name"
UpdateSourceTrigger="LostFocus" >
<Binding.ValidationRules>
<validators:UserNameValidator/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
control template
为ErrorTemplate
:
<ControlTemplate x:Key="validationTemplate">
<DockPanel>
<Ellipse Width="12" Height="12"
Fill="Red" HorizontalAlignment="Center"
VerticalAlignment="Center"/>
<AdornedElementPlaceholder/>
</DockPanel>
</ControlTemplate>
style
使用工具提示为错误内容创建文本框<Style x:Key="textBoxInError" TargetType="{x:Type TextBox}">
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="true">
<Setter Property="ToolTip"
Value="{Binding RelativeSource={x:Static RelativeSource.Self},
Path=(Validation.Errors)[0].ErrorContent}"/>
</Trigger>
</Style.Triggers>
</Style>
:
请注意,只要存在通过触发器设置的错误,就会设置工具提示。
{{1}}