简体   繁体   中英

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. I have a viewModel called MainWindowViewModel in this project. 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. So I can use this class for other ViewModels also.

If there is a better solution then passing ViewModel name as parameter please describe.

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 ...

In short, the object value is your parameter.

In long, I think you should do some reading on how to use validations, and revise your logic and code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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