我在验证方面有问题,到目前为止,这是一场真正的斗争。我修改了一些代码,并阅读了很多关于这方面的内容,并且遵循了下面的指南:http://developingfor.net/2009/10/13/using-custom-validation-rules-in-wpf/,但是我遇到了问题。验证不是开火,我也找不到原因!我会发一些我的代码。
public class RequiredFields : ValidationRule
{
private String _errorMessage = String.Empty;
public string ErrorMessage
{
get { return _errorMessage; }
set { _errorMessage = value; }
}
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
var str = value as string;
if (String.IsNullOrEmpty(str))
{
return new ValidationResult(false, this.ErrorMessage);
}
return new ValidationResult(true, null);
}
}XAML:
<Style
x:Key="textBoxInError"
TargetType="{x:Type TextBox}">
<Style.Triggers>
<Trigger
Property="Validation.HasError"
Value="true">
<Setter
Property="ToolTip"
Value="{Binding (Validation.Errors)[0].ErrorContent, RelativeSource={x:Static RelativeSource.Self}}" />
<Setter
Property="Background"
Value="Red" />
<Setter
Property="Foreground"
Value="White" />
</Trigger>
</Style.Triggers>
</Style>TextBox XAML:
<TextBox x:Name="txtFirstName" Validation.ErrorTemplate="{StaticResource validationTemplate}" HorizontalAlignment="Left" Height="23" Margin="156,62,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="149">
<TextBox.Text>
<Binding Path="FirstName" UpdateSourceTrigger="PropertyChanged" Mode="TwoWay">
<Binding.ValidationRules>
<validators:RequiredFields ErrorMessage="Name is Required" />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>XAML窗口的CodeBehind如下:
RequiredFields ss = new RequiredFields();
this.DataContext = ss;但出于某种原因,我不会看到事件的爆发。如果我在ValidationResult中标记一个断点,它不会做任何事情。
发布于 2014-10-27 02:58:17
您的ValidationRule RequiredFields也用作DataContext,但未声明属性FirstName。因此,绑定实际上是失败的。您应该定义一个单独的ViewModel,如果您仍然希望将RequiredFields用作DataContext,则必须添加如下所示的属性FirstName:
public class RequiredFields : ValidationRule, INotifyPropertyChanged
{
private String _errorMessage = String.Empty;
public string ErrorMessage
{
get { return _errorMessage; }
set { _errorMessage = value; }
}
public override ValidationResult Validate(object value,
CultureInfo cultureInfo)
{
var str = value as string;
if (String.IsNullOrEmpty(str))
{
return new ValidationResult(false, this.ErrorMessage);
}
return new ValidationResult(true, null);
}
//Implements INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string prop){
var handler = PropertyChanged;
if(handler != null) handler(this, new PropertyChangedEventArgs(prop));
}
//add the property FirstName
string _firstName;
public string FirstName {
get {
return _firstName;
}
set {
if(_firstName != value) {
_firstName = value;
OnPropertyChanged("FirstName");
}
}
}
}上面的代码只是一个快速修复和演示解决方案,而不是实际的实践。您应该创建一些实现INotifyPropertyChanged的基类,实现单独的 ViewModel,而不是使用一些现有的ValidationRule。
https://stackoverflow.com/questions/26578711
复制相似问题