From 623811323c2e3663835dbb4b23ab70becb4d890d Mon Sep 17 00:00:00 2001 From: dbchandra23 <130417839+dbchandra23@users.noreply.github.com> Date: Sun, 28 Apr 2024 15:29:46 +1000 Subject: [PATCH] Update reactive-view-model.md I had great difficulty and confusion to properly use ReactiveUI with Avalonia. Due to the felxible nature of Avalonia, there was many different ways I found in the forums and even the current docs that is not really great for ReactiveUI. I have provided a simple example that works elegantly with the 11.x Avalonia and ReactiveUI. --- .../reactiveui/reactive-view-model.md | 62 +++++++++++++++++++ 1 file changed, 62 insertions(+) diff --git a/docs/concepts/reactiveui/reactive-view-model.md b/docs/concepts/reactiveui/reactive-view-model.md index 097b3a841..db5b5f93d 100644 --- a/docs/concepts/reactiveui/reactive-view-model.md +++ b/docs/concepts/reactiveui/reactive-view-model.md @@ -59,3 +59,65 @@ Any change to the view model description property is achieved using the `set` ac When _Avalonia UI_ uses the binding to **Update** the view model, the `set` accessor ensures that any parts of the view model that depend on the description property can also react to the change if necessary. On the next page, you will learn how a reactive command acts as a special case of the view model update. + +## Performing Data Validation +ReactiveUI provides the ability to perform data validation from the ViewModel that integrates well with the Avalonia fluent controls. The example shows how this can be done. The example is for a ViewModel that exposes a directory path string that is bounded to a TextBox control on the View. + +Steps to enable data validation on the ViewModel: +1. Download the ReactiveUI.Validation nuget package (for desktop applications) +2. Change the inheritance of the ViewModel to ReactiveValidationObject +3. Include a this.ValidationRule in the ViewModel constructor, which provides the validation check for the ViewModel property and corresponding validation error message. + +The code below shows the MainWindowViewModel.cs and MainWindow.axaml +```C# +using System.IO; +using ReactiveUI; +using ReactiveUI.Validation.Extensions; +using ReactiveUI.Validation.Helpers; + +namespace AvaloniaApplication3.ViewModels; + +public class MainWindowViewModel : ReactiveValidationObject +{ + private string _directoryPath = string.Empty; + + public string DirectoryPath + { + get => _directoryPath; + set => this.RaiseAndSetIfChanged(ref _directoryPath, value); + } + + public MainWindowViewModel() + { + DirectoryPath = "C:\\BogusPath\\"; + this.ValidationRule( + vm => vm.DirectoryPath, + path => Directory.Exists(path), + "You must specify a valid directory path."); + + } +} +``` +```xaml + + + + + +``` +Below is the output: + +![Avalonia-ReactiveUI-DataValidation](https://github.com/AvaloniaUI/avalonia-docs/assets/130417839/75aede6b-f8cc-4bb8-8520-f9a8f24aa779)