我正在尝试验证一些控件,当我输入断点并运行应用程序时,我的customValidation类被调用,我可以通过我的断点,逻辑似乎工作正常但是当我在文本框中输入数据时,UpdateSourceTrigger不会火和文本框边框仍然是红色,我发布我的代码请告诉我我做错了什么。
自定义类:
public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
{
// try
//{
string letter = "/[a-zA-Z]/";
string number = "/[0-9]/";
string val = null;
if (value != null)
{
val = value.ToString();
}
String regex="/^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/";
if(this.ControlName.ToString()=="username")
{
if (val == "" || val == null )
{
return new ValidationResult(false, "Please enter a valid Username ");
}
}
else if(this.ControlName.ToString()=="password")
{
if (val == null || val == "" || val.Length < 4 || val.Length > 15 )
{
return new ValidationResult(false, "Please enter a Valid password");
}
}
return new ValidationResult(true, null);
// }
}
XAML页面:
<TextBox HorizontalAlignment="Stretch" Grid.Column="1" Grid.Row="3" Name="txtusername" Height="23" TextWrapping="Wrap" VerticalAlignment="Center" >
<TextBox.Text>
<Binding Mode="TwoWay" Path="username" UpdateSourceTrigger="PropertyChanged" ValidatesOnDataErrors="True" ValidatesOnNotifyDataErrors="True" NotifyOnValidationError="True">
<Binding.ValidationRules>
<local:CustomValidator ControlName="username" ValidatesOnTargetUpdated="True"/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
答案 0 :(得分:0)
此代码适用于我:
<TextBox HorizontalAlignment="Stretch" Name="txtusername" Height="23" TextWrapping="Wrap" VerticalAlignment="Center" >
<TextBox.Text>
<Binding Path="username" UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<l:CustomValidator ControlName="username" />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new Test();
}
}
public class Test
{
public string username { get; set; }
}
public class CustomValidator : ValidationRule
{
public string ControlName { get; set; }
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
string letter = "/[a-zA-Z]/";
string number = "/[0-9]/";
string val = null;
if (value != null)
{
val = value.ToString();
}
String regex = "/^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/";
if (this.ControlName.ToString() == "username")
{
if (val == "" || val == null)
{
return new ValidationResult(false, "Please enter a valid Username ");
}
}
else if (this.ControlName.ToString() == "password")
{
if (val == null || val == "" || val.Length < 4 || val.Length > 15)
{
return new ValidationResult(false, "Please enter a Valid password");
}
}
return new ValidationResult(true, null);
}
}