Dimitris
Dimitris

Reputation: 755

How to handle Behaviors in Prism with Xamarin.Forms

How to handle behaviors with Prism? I have the following code and I would like to know how to handle the "enrtyEmail.IsValid" property? How can I find out in the ViewModel the status of the EmailValidatorBehavior ?

<Entry x:Name="entryEmail">  
  <Entry.Behaviors>  
    <local:EmailValidatorBehavior />  
  </Entry.Behaviors>  
</Entry>      

Upvotes: 0

Views: 1145

Answers (1)

Dan Siegel
Dan Siegel

Reputation: 5799

A Behavior is a BindableObject, so you can simply add a BindableProperty to your EmailValidatorBehavior.

public class EmailValidatorBehavior : BehaviorBase<Entry>
{
    public static readonly BindableProperty IsEmailValidProperty =
        BindableProperty.Create( nameof( IsEmailValid ), typeof( bool ), typeof( EmailValidatorBehavior ), false, BindingMode.OneWayToSource );

    public bool IsEmailValid
    {
        get { return (bool)GetValue( IsEmailValidProperty ); }
        set { SetValue( IsEmailValidProperty, value ); }
    }
}

and then bind to that property from your ViewModel

<Entry Text="{Binding EmailAddress}">  
  <Entry.Behaviors>  
    <local:EmailValidatorBehavior IsEmailValid="{Binding IsEmailValid}" />  
  </Entry.Behaviors>  
</Entry> 

EDIT: Note that without setting the BindingMode the binding will not propagate from the Behavior to the ViewModel. Given the nature of the setting the most appropriate BindingMode would be OneWayToSource as this makes the property effectively read only for the ViewModel.

see https://github.com/dansiegel/Validation-With-Prism-Behavior for a working example

Upvotes: 2

Related Questions