Search code examples
c#mvvm.net-mauieventtocommandmaui-community-toolkit

.Net Maui EventToCommand for unfocus event for Entry throws System.InvalidCastException


Am building a new App in .Net Maui using VS 2022 Preview. I am using CommunityToolkit.Mvvm

I have an entry field. When this field loses focus, I want to trigger a command.

My xaml is :

  <Entry Margin="10,0,10,0" 
                  
                   MaxLength="20"
                  
                   IsEnabled="{Binding IsNotBusy}"
                   PlaceholderColor="Red"
                   >
            <Entry.Behaviors>
                <toolkit:EventToCommandBehavior EventName="Unfocused" Command="{Binding GetDetailsCommand}"></toolkit:EventToCommandBehavior>
            </Entry.Behaviors>

Everything compiles and runs. But when the entry field loses focus I get a System.InvalidCastException.

What am I doing wrong?

Could this be because I am using the sourcegenerators in the mvvm toolkit?

[ICommand]
public async void GetDetails() 

Kindly help.

Edit : I noticed that source generator generates IAsyncRelayCommand and not an ICommand object. That is what prompted me to ask the above question.


Solution

  • Actually, THAT is exactly the case. I changed to implementing a normal Command instead of IAsyncRelayCommand generated by source generators and everything works.

    I went through various blogs and YouTube videos and realised that there is not much stuff available on "Unfocused" event and its EventToCommand behaviour. That got me thinking that it is ME doing something wrong because the problem must be trivial. Wonder why it was not pointed out earlier.

    My recommendation? Please follow what is already there and established, when working with .Net MAUI GA instead of jumping ahead and trying to implement the latest stuff after watching videos about new features. Spent one entire day hunting for a solution. Actually, was so frustrated at one point that started thinking about shifting to Flutter, believing that .Net MAUI is unstable.