Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# WPF属性验证检查属性是否有效_C#_Wpf_Validation_Xaml - Fatal编程技术网

C# WPF属性验证检查属性是否有效

C# WPF属性验证检查属性是否有效,c#,wpf,validation,xaml,C#,Wpf,Validation,Xaml,在我的C#WPF应用程序中有一个ViewModel,它包含几个类似这样的属性 public class ExecutionsCreateViewModel : ValidationViewModelBase { [Required(ErrorMessage = "Execution name is required.")] [StringLength(60, ErrorMessage = "Execution name is too long.")] public str

在我的C#WPF应用程序中有一个
ViewModel
,它包含几个类似这样的属性

public class ExecutionsCreateViewModel : ValidationViewModelBase
{
    [Required(ErrorMessage = "Execution name is required.")]
    [StringLength(60, ErrorMessage = "Execution name is too long.")]
    public string ExecutionName { get; set; }
    [...]
}
这是我的
ValidationViewModelBase

public abstract class ValidationViewModelBase : IDataErrorInfo
{
    string IDataErrorInfo.Error
    {
        get
        {
            throw new NotSupportedException("IDataErrorInfo.Error is not supported.");
        }
    }
    string IDataErrorInfo.this[string propertyName]
    {
        get
        {
            if (string.IsNullOrEmpty(propertyName))
            {
                throw new ArgumentException("Invalid property name", propertyName);
            }
            string error = string.Empty;
            var value = GetValue(propertyName);
            var results = new List<ValidationResult>(1);
            var result = Validator.TryValidateProperty(
                value,
                new ValidationContext(this, null, null)
                {
                    MemberName = propertyName
                },
                results);
            if (!result)
            {
                var validationResult = results.First();
                error = validationResult.ErrorMessage;
            }
            return error;
        }
    }
    private object GetValue(string propertyName)
    {
        PropertyInfo propInfo = GetType().GetProperty(propertyName);
        return propInfo.GetValue(this);
    }
}
我试过使用
Validator.ValidateProperty
(,)但它不起作用和/或太乱了。我还玩了一些小把戏,比如

    try
    {
        ExecutionName = ExecutionName;
    }
    catch(Exception ex)
    {
        MessageBox.Show(ex.Message);
        return;
    }
但它在某些情况下不起作用,看起来也不太专业。 也许
ValidateProperty
是关键,但经过许多“教程”之后,我仍然不知道如何满足我的需要

还有第二件小事。属性始终验证其属性,因此当用户收到新表单时,
ExecutionName
将始终为空,因此
Required
属性将其标记为无效,以便控件将自动变为红色。是否有方法在初始化时跳过验证

问题是,如果某些属性当前有效或无效,我不知道如何签入
Create
方法

private void Create()
{
    if(/*check if property is invalid*/)
    {
        MessageBox.Show(/*property ErrorMessage*/);
        return;
    }

    //Do something with valid properties
}}
与您在
ValidationViewModelBase
类中的操作相同,例如:

private void Create()
{
    var value = this.ExecutionName; //the property to validate
    var results = new List<ValidationResult>();
    var result = Validator.TryValidateProperty(
        value,
        new ValidationContext(this, null, null)
        {
            MemberName = "ExecutionName" //the name of the property to validate
        },
        results);

    if (!result)
    {
        var validationResult = results.First();
        MessageBox.Show(validationResult.ErrorMessage);
    }

    //...
}
private void Create()
{
var value=this.ExecutionName;//要验证的属性
var results=新列表();
var result=Validator.TryValidateProperty(
价值
新的ValidationContext(this,null,null)
{
MemberName=“ExecutionName”//要验证的属性的名称
},
结果);
如果(!结果)
{
var validationResult=results.First();
MessageBox.Show(validationResult.ErrorMessage);
}
//...
}
问题是,如果某些属性当前有效或无效,我不知道如何签入
Create
方法

private void Create()
{
    if(/*check if property is invalid*/)
    {
        MessageBox.Show(/*property ErrorMessage*/);
        return;
    }

    //Do something with valid properties
}}
与您在
ValidationViewModelBase
类中的操作相同,例如:

private void Create()
{
    var value = this.ExecutionName; //the property to validate
    var results = new List<ValidationResult>();
    var result = Validator.TryValidateProperty(
        value,
        new ValidationContext(this, null, null)
        {
            MemberName = "ExecutionName" //the name of the property to validate
        },
        results);

    if (!result)
    {
        var validationResult = results.First();
        MessageBox.Show(validationResult.ErrorMessage);
    }

    //...
}
private void Create()
{
var value=this.ExecutionName;//要验证的属性
var results=新列表();
var result=Validator.TryValidateProperty(
价值
新的ValidationContext(this,null,null)
{
MemberName=“ExecutionName”//要验证的属性的名称
},
结果);
如果(!结果)
{
var validationResult=results.First();
MessageBox.Show(validationResult.ErrorMessage);
}
//...
}

“是否有办法在初始化时跳过验证”-是的,初始化不应验证任何内容,例如直接设置字段值。属性可以用于UI和用户验证,但viewmodel和属性都没有实现通知。当我将属性绑定到XML对象属性时,该属性会在初始化时自动调用,因为对象属性会为自身寻找初始值。将
模式设置为
OneWayToSource
没有帮助。当
validatesOnDaerRors
设置为true时,即使在初始化时也会检查验证“是否有方法在初始化时跳过验证”-是的,初始化不应验证任何内容,例如通过直接设置字段值。属性可以用于UI和用户验证,但viewmodel和属性都没有实现通知。当我将属性绑定到XML对象属性时,该属性会在初始化时自动调用,因为对象属性会为自身寻找初始值。将
模式设置为
OneWayToSource
没有帮助。当
validatesOnDaerRors
设置为true时,即使在初始化时也会检查验证,这是一个很好的方法。我决定使用
ValidateValue
并捕获异常(如果发生),那么异常消息就是我需要的错误消息,这样我就不需要
结果了。这是一个好方法。我决定使用
ValidateValue
并捕获异常(如果发生),那么异常消息就是我需要的错误消息,这样我就不需要
结果了。