0

In my learning NET MAUI app I want to pass a behavior command parameter as string, like this:

Entry x:Name="name" Text="{Binding Name}"
       ClearButtonVisibility="WhileEditing">
    <Entry.Behaviors>
        <toolkit:EventToCommandBehavior
            EventName="TextChanged"
            Command="{Binding ValidateCommand}"
            CommandParameter="'Name'" />
    </Entry.Behaviors>
</Entry>

In the code behind I am doing a validation:

public delegate void NotifyWithValidationMessages(Dictionary<string, string?> validationDictionary);

public class BaseViewModel : ObservableValidator
{
    public event NotifyWithValidationMessages? ValidationCompleted;

    public virtual ICommand ValidateCommand => new RelayCommand<string?>((string? propertyName) =>
    {
        ClearErrors();

        if (!string.IsNullOrWhiteSpace(propertyName))
        {
            ValidateProperty(propertyName);
        }
        else
            ValidateAllProperties();
        
        var validationMessages = this.GetErrors()
                                     .ToDictionary(k => k.MemberNames.First().ToLower(), v => v.ErrorMessage);
    
        ValidationCompleted?.Invoke(validationMessages);
    });

    public BaseViewModel() : base()
    {}
}

When the propertyName parameter is null, and the ValidateAllProperties() are triggered, everything works fine, but when I have a parameter line "Name", then I get the following error when the ValidateProperty(propertyName) got called :

System.ArgumentException: 'The value for property 'ValidateCommand' must be of type 'System.Windows.Input.ICommand'. (Parameter 'value')'

I am using CommunityToolkit.Mvvm v8.0.0

thnx

Wasyster
  • 2,279
  • 4
  • 26
  • 58

1 Answers1

0

ValidateProperty method: Validates a property with a specified name and a given input value.(More info you could refer to ObservableValidator.ValidateProperty(Object, String) Method)

So if you want to Validate a specific property, you could try this:

ValidateProperty(Name,propertyName); // the first Name gets the value of the Name property; propertyName is the parameter you pass from xaml

Here is my complete code:

private string name;

[Required]
[StringLength(255)]
[MinLength(2)]
public string Name
{
    get => this.name;
    set
    {
        SetProperty(ref this.name, value);
    }
}

public virtual ICommand ValidateCommand => new RelayCommand<string?>((string? propertyName) =>
{
    ...

    if (!string.IsNullOrWhiteSpace(propertyName))
    {
        ValidateProperty(Name,propertyName); // ***just change this line
    }
    else
        ValidateAllProperties();

    ...
});

Hope it works for you.

Liqun Shen-MSFT
  • 3,490
  • 2
  • 3
  • 11