验证ReactiveUi 5

时间:2013-09-17 14:03:00

标签: c# wpf mvvm reactiveui

我使用的是ReactiveUI 5,但现在我需要在我的ViewModel中进行验证,所以我使用了文档中描述的ReactiveValidatedObject。配置在版本4示例中完全相同,但似乎不起作用。运行示例代码效果很好,但是对于版本5它不起作用,我的ValidatesViaMethod属性中定义的验证方法不会被触发。

我仔细检查了每一件事,它等同于示例代码,只需要一个简单的文本框验证。

我不知道可以做任何其他事情。有没有其他方法可以使用ReactiveUI进行验证?除了版本4之外,我找不到任何文档或示例。

这是我的ViewMode,我使用版本4的ReactiveValidatedObject和版本5的路由。

public class InputViewModel : ReactiveValidatedObject , IRoutableViewModel
{
    bool val;
    bool invalid = false;

    public InputViewModel(IScreen hostscreen)
    {            
        ValidationObservable.Subscribe(x => IsValid = this.IsObjectValid());                
        var whenAnyValuesChange = this.WhenAny(x => x.IsValid, x => x.Value);                       
        HostScreen = hostscreen ?? RxApp.DependencyResolver.GetService<IScreen>();
    }

    [ValidatesViaMethod(AllowBlanks = false, AllowNull = false, Name = "IsNameValid", ErrorMessage = "Favor informe o nome corretamente")]
    public string Name
    {
        get {  return _name; }
        set 
        {
            this.RaiseAndSetIfChanged(ref _name, value);
        }
    }

    public bool IsNameValid(string name)
    {
        return name.Length >= 2;
    }

    public IScreen HostScreen
    {
        get;
        private set;
    }

    public string UrlPathSegment
    {
        get { return "InputView"; }
    }

    public Simulation Simulation { get; set; }

    private bool _IsValid;
    public bool IsValid
    {
        get { return _IsValid; }
        set { this.RaiseAndSetIfChanged(ref _IsValid, value); }
    }
}

2 个答案:

答案 0 :(得分:1)

如果您需要更多控制验证,我建议您尝试FluentValidation。它与任何MVVM框架都很好地集成,并且与基于属性的验证相比,使用InlineValidator可以处理更复杂的验证方案。我在大多数项目中都是自己使用它。

答案 1 :(得分:0)

如果要将FluentValidationReactiveUI一起使用,则可以执行以下操作:

验证器

public sealed class ContactViewModelValidator 
    : AbstractValidator<ContactViewModel>
{
    pulbic ContactViewModelValidator()
    {
        RuleFor(vm => vm.FirstName)
            .Required()
            .WithMessage("The first name is required");
        // more rules
    }
}

ViewModel

public sealed class ContactViewModel : ReactiveObject, ISupportsActivation
{
    public ViewModelActivator Activator { get; } = new ViewModelActivator();

    [Reactive] public string FirstName { get; set; }
    [Reactive] public string FirstNameErrorMessage { get; set; }

    // other properties

    private IValidator<ContactViewModel> Validator { get; }

    public ContactViewModel(IValidator<ContactViewModel> validator)
    {
        Validator = validator ?? throw new ArgumentNullException(nameof(validator));

         this.WhenActivated(d =>
         {
             ActivateValidation(this, d);

             // other activations
         });
    }

    // since this is static, you can put it in an external class
    private static void ActivateValidation(ContactViewModel viewModel, CompositeDisposable d)
    {
        var validationSubject = new Subject<ValidationResult>().DisposeWith(d);
        viewModel.WhenAnyValue(vm => vm.FirstName /* other properties */)
            .Select(_ => viewModel)
            .Select(viewModel.Validator.Validate)
            .ObserveOn(RxApp.MainThreadScheduler)
            .SubscribeOn(RxApp.MainThreadScheduler)
            .Subscribe(result => validationSubject.OnNext(result))
            .DisposeWith(d);

        validationSubject
            .Select(e => e.Errors)
            .ObserveOn(RxApp.MainThreadScheduler)
            .SubscribeOn(RxApp.MainThreadScheduler)
            .Subscribe(errors =>
            {
                using (viewModel.DelayChangeNotifications())
                {
                    viewModel.FirstNameErrorMessage = 
                        errors.GetMessageForProperty(nameof(viewModel.FirstName));

                    // handle other properties
                }
            })
            .DisposeWith(d);
    }
}

扩展名

public static class ValidationFailureExtensions
{
    // This is an example that gives you all messages,
    // no matter if they are warnings or errors.
    // Provide your own implementation that fits your need.
    public static string GetMessageForProperty(this IList<ValidationFailure> errors, string propertyName)
    {
        return errors
            .Where(e => e.PropertyName == propertyName)
            .Select(e => e.ErrorMessage)
            .Aggregate(new StringBuilder(), (builder, s) => builder.AppendLine(s), builder => builder.ToString());
    }
}

查看

public partial class ContactControl : IViewFor<ContactViewModel>
{
    public ContactControl()
    {
        InitializeComponent();
    }

    object IViewFor.ViewModel
    {
        get => ViewModel;
        set => ViewModel = value as ContactViewModel;
    }

    public ContactViewModel ViewModel
    {
        get => DataContext as ContactiewModel;
        set => DataContext = value;
    }
}
d:DataContext="{d:DesignInstance Type=local:ContactViewModel, IsDesignTimeCreatable=True}" 
<UserControl.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="..." />
                <ResourceDictionary>
                    <Style BasedOn="{StaticResource {x:Type TextBlock}}" 
                           TargetType="TextBlock"
                           x:Key="ErrorMessageTextBlock">
                            <Style.Setters>
                                <Setter Property="Foreground" Value="Red" />
                                <Setter Property="Height" Value="Auto" />
                                <Setter Property="TextWrapping" Value="Wrap" />
                                <Setter Property="Padding" Value="4" />
                        </Style.Setters>
                            <Style.Triggers>
                                <Trigger Property="Text" Value="{x:Null}">
                                    <Setter Property="Height" Value="0" />
                                    <Setter Property="Visibility" Value="Collapsed" />
                                </Trigger>
                                <Trigger Property="Text" Value="">
                                    <Setter Property="Height" Value="0" />
                                    <Setter Property="Visibility" Value="Collapsed" />
                                </Trigger>
                            </Style.Triggers>
                    </Style>
                </ResourceDictionary>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </UserControl.Resources>
<TextBlock Text="{Binding FirstNameErrorMessage}"
           Style="{StaticResource ErrorMessageTextBlock}" />