0

So I have this simple application that has a button, that's it. And the button has a command property bound to a command.

This is the command it is bound to.

public class StartAsyncCommand : ICommand
    {
        private Task _execute;
        public StartAsyncCommand(Task Execute)
        {
            _execute = Execute;
        }
        public bool CanExecute(object parameter)
        {
            return true;
        }

        public void Execute(object parameter)
        {
            _execute.Start();
        }

        public event EventHandler CanExecuteChanged;
    }

And in the ViewModel this is what I got.

public StartAsyncCommand StartCommand { get; }

        public MoveMouseModel()
        {
            StartCommand = new StartAsyncCommand(MoveMove());
        }

        public async Task MoveMove()
        {
            MessageBox.Show("First Message..");
            await Task.Delay(2000);
            MessageBox.Show("Second Message..");
        }

XAML

<Grid>
    <Button Width="100"
            Height="25"
            Content="Async?"
            Command="{Binding MoveMouseModel.StartCommand}"/>
</Grid>

When I start the application, that those messageboxes show even though I didnt click the button. What can I do to prevent this?

1 Answers1

1

You are passing the result of MoveMove to your StartAsyncCommand class, not the actual method

 public MoveMouseModel()
 {
      StartCommand = new StartAsyncCommand(MoveMove()); //<-- MoveMove() is executed
 }

Should work when you actually pass the method instead and call it inside of StartAsyncCommand instead

eg. public StartAsyncCommand(Func<Task> fnc) {...} as constructor and then just executing the func when the actual command is used

wondering why your visual studio is not displaying you some "this method is not awaited" info message though ..

X39
  • 789
  • 6
  • 22
  • 1
    Ohhh! Right right! I need to look into the Func delegate a bit more, I totally missed that I was passing the result and not the actual method. Thanks! – Ada Davidsson Sep 25 '18 at 16:49
  • Can expand to full example if you want. You also may want to look into some more generic implementation. As example: https://stackoverflow.com/questions/22285866/why-relaycommand contains one such – X39 Sep 25 '18 at 16:51
  • Yeah i've heard about RelayCommands never gotten into them, I guess this is when I start, appreciate it! – Ada Davidsson Sep 25 '18 at 17:02