Search code examples
xamarinmvvmbehavior

Communication between behavior and viewmodel in xamarin


I have a custom behavior to validate telephonenumbers in my view attached to a entry:

<Entry x:Name="phoneNumber" Text="{Binding TelephoneNum, Mode=TwoWay}">
    <Entry.Behaviors>
        <behaviors:TelNumBehavior x:Name="NumValidatorUser" />
    </Entry.Behaviors>
</Entry>

I am using the mvvm pattern with view and viewmodel. The behavior has a bindable isValid property. How can I use that value in my Viewmodel? How can these two classes communicate? The messaging-service is not an option for me, because I have multiple behaviors and I need to validate them all. Is there a way to access the isValid-att of the behaviors?


Solution

  • Name your page, to be referenced later on:

    <ContentPage x:Name="Root" etc, etc>
    

    in your behavior set the path and source to the page's binding-context:

    <Entry x:Name="phoneNumber" Text="{Binding TelephoneNum, Mode=TwoWay}">
        <Entry.Behaviors>
                 <behaviors:TelNumBehavior x:Name="NumValidatorUser" />
                IsValid="{Binding Source={x:Reference Root}, 
                          Path=BindingContext.YourPropertyIsValid, Mode=TwoWay}"/>
        </Entry.Behaviors>        
    </Entry>