2

我使用的是 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); }
    }
}
4

2 回答 2

1

如果您需要对验证进行更多控制,我建议您尝试一下FluentValidation。它与任何 MVVM 框架很好地集成,通过使用 InlineValidator,您可以处理与基于属性的验证相比更复杂的验证场景。我自己在我的大部分项目中都使用它。

于 2013-10-22T14:16:40.063 回答
0

如果你想使用FluentValidationwith ReactiveUI,你可以这样做:

验证器

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

视图模型

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}" />
于 2019-08-06T10:06:04.603 回答