简体   繁体   English

传递viewmodel类名作为参数来验证从ValidationRule类继承的类的方法

[英]passing a viewmodel class name as parameter to validate method of a class inheriting from ValidationRule class

I have a class called ContainsValidationRule in my Project Sample. 我的项目示例中有一个名为ContainsValidationRule的类。 I have a viewModel called MainWindowViewModel in this project. 我在这个项目中有一个名为MainWindowViewModel的viewModel。 The code looks something like : 该代码看起来像:

namespace Sample
{
    using System.Globalization;
    using System.Linq;
    using System.Windows.Controls;

    public class ContainsValidationRule : ValidationRule
    {
        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            var result = MainWindowViewModel.CurrentInstance.Items.Any(x => x.ToLower(cultureInfo).Contains((value as string).ToLower(cultureInfo)));
            return new ValidationResult(result, "No Reason");
        }
    }
}

It works well. 它运作良好。 But Instead of having MainViewViewModel hard-coded I want to pass it as a parameter to Validate Method. 但是,我不想将MainViewViewModel硬编码,而是将其作为参数传递给Validate Method。 So I can use this class for other ViewModels also. 因此,我也可以将此类用于其他ViewModel。

If there is a better solution then passing ViewModel name as parameter please describe. 如果有更好的解决方案,请传递ViewModel名称作为参数。

Well, I must say your code is a bit perplexing. 好吧,我必须说您的代码有些困惑。 Usually you'll use the value as what you're validating. 通常,您将使用该值作为您要验证的值。

For example: 例如:

<TextBox.Text>
 <Binding Path="SomeProperty" UpdateSourceTrigger="PropertyChanged">
     <Binding.ValidationRules>
         <validations:YourValidationName ValidatesOnTargetUpdated="True" />
     </Binding.ValidationRules>
 </Binding>
</TextBox.Text>

What this will do, is whenever you update your textbox, it'll validate it and if it's invalid,you'll get the red border (or whatever style you set) and the error. 这样做的目的是,每当您更新文本框时,它将对其进行验证,如果无效,则会显示红色边框(或您设置的任何样式)和错误。

For on the other hand, totally ignore the object that you are validation on, and will use the hardcoded MainWindowViewModel.CurrentInstance.Items... , to check things ... 另一方面,对于,请完全忽略要验证的对象,并将使用硬编码的MainWindowViewModel.CurrentInstance.Items...来检查事物...

In short, the object value is your parameter. 简而言之, object value就是您的参数。

In long, I think you should do some reading on how to use validations, and revise your logic and code. 总之,我认为您应该阅读有关如何使用验证的知识,并修改逻辑和代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM