要求:我们有TextBox,当它为空并且失去焦点时,文本框会将自己标记为“需要填充”并引发弹出窗口。
实施:到目前为止,我已成为以下解决方案:
重要说明:我无法负担代码的使用,因为这对于ant文本框应该是通用的。
问题是当文本框为空并失去焦点时,我的代码无效。
<Window.Resources>
<Style TargetType="{x:Type TextBox}">
<Setter Property="Validation.ErrorTemplate">
<Setter.Value>
<ControlTemplate>
<DockPanel>
<Grid DockPanel.Dock="Right" Width="16" Height="16" VerticalAlignment="Center" Margin="3 0 0 0">
<Ellipse Width="16" Height="16" Fill="Red" />
<Ellipse Width="3" Height="8" VerticalAlignment="Top" HorizontalAlignment="Center" Margin="0 2 0 0" Fill="White" />
<Ellipse Width="2" Height="2" VerticalAlignment="Bottom" HorizontalAlignment="Center" Margin="0 0 0 2" Fill="White" />
</Grid>
<Border BorderBrush="Red" BorderThickness="2" CornerRadius="2">
<AdornedElementPlaceholder />
</Border>
</DockPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
<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>
</Window.Resources>
<Grid>
<TextBox Height="20" Width="100" />
<TextBox Grid.Row="0" Grid.Column="1" VerticalAlignment="Center" HorizontalAlignment="Left" MinWidth="150" MaxWidth="180" Margin="5,0">
<TextBox.Text>
<Binding Path="IncidentName" Mode="TwoWay" NotifyOnSourceUpdated="True" UpdateSourceTrigger="LostFocus">
<Binding.ValidationRules>
<validators:EmptyTextValidationRule />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
</Grid>
EmptyTextValidationRule:
public class EmptyTextValidationRule : ValidationRule
{
private string m_errorText;
private const string TEXT_REQUERIED = "Text filed should not be empty";
public EmptyTextValidationRule()
{
}
public string ErrorText
{
get { return m_errorText; }
set
{
m_errorText = value;
}
}
public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
{
string enterendText = value.ToString();
if (string.IsNullOrEmpty(enterendText))
{
if (string.IsNullOrEmpty(ErrorText))
return new ValidationResult(false, TEXT_REQUERIED);
else
return new ValidationResult(false, ErrorText);
}
return new ValidationResult(true, null);
}
}
答案 0 :(得分:1)
这不是尝试回答您的问题,而只是指出代码中的错误:
public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
{
string enterendText = value.ToString(); //<< You'll get error here if value is null
if (string.IsNullOrEmpty(enterendText)) //<< No point checking here... too late!
{
if (string.IsNullOrEmpty(ErrorText))
return new ValidationResult(false, TEXT_REQUERIED);
else
return new ValidationResult(false, ErrorText);
}
return new ValidationResult(true, null);
}
使用此代码,如果value
曾null
,那么您在第一个if
语句条件中会收到错误...您应该执行以下操作:< / p>
string enterendText = string.Empty;
if (value == null || (enterendText = value.ToString()).Trim() == string.Empty)
{
...
}