ReactiveUI, WPF and Validation

时光总嘲笑我的痴心妄想 提交于 2020-07-18 13:47:02

问题


I've seen that ReactiveUI had validation features in the past. Currently, with version 6.5, I cannot find anything related to it.

Do you know if there's a more or less official way to deal with validation tasks in WPF using ReactiveUI?


回答1:


Overall consensus on RxUI slack group is that people are exposing extra validation properties, e.g. split UserName and UserNameError (which is null if there is no error). Then use the platform’s validation/error mechanism to bring to user’s attention.




回答2:


You cant take a look at this repo https://github.com/reactiveui/ReactiveUI.Validation, also available on NuGet gallery.

This solution is based on MVVM pattern, so your ViewModels must implement ISupportsValidation, add rules (ValidationHelper properties) and bind to the validation rules from the View.

ViewModel

public class SampleViewModel : ReactiveObject, ISupportsValidation
{
    public ValidationContext ValidationContext => new ValidationContext();

    // Bindable rule
    public ValidationHelper ComplexRule { get; set; }

    public SampleViewModel()
    {
         // name must be at least 3 chars - the selector heee is the property name and its a single property validator
         this.ValidationRule(vm => vm.Name, _isDefined, "You must specify a valid name");
    }
}

View

public class MainActivity : ReactiveAppCompatActivity<SampleViewModel>
{
    public EditText nameEdit { get; set; }

    public TextInputLayout til { get; set; }

    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        // Set our View from the "main" layout resource
        SetContentView(Resource.Layout.Main);

        WireUpControls();

        // bind to an Android TextInputLayout control, utilising the Error property
        this.BindValidation(ViewModel, vm => vm.ComplexRule, til);
    }
}

The View sample is taking advantage of the DroidExtensions (automatically added for Mono.Droid projects), but you can bind the error message to any control of your View.

I hope it helps.

Best regards.



来源:https://stackoverflow.com/questions/34952572/reactiveui-wpf-and-validation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!