[英]How do I prevent my command to run on Application Load
So I have this simple application that has a button, that's it. 因此,我有一个具有按钮的简单应用程序,仅此而已。 And the button has a command property bound to a command.
并且按钮具有绑定到命令的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. 而在ViewModel中,这就是我得到的。
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 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?
我该怎么做才能避免这种情况?
You are passing the result of MoveMove
to your StartAsyncCommand
class, not the actual method 你是路过的结果
MoveMove
您StartAsyncCommand
类,而不是实际的方法
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 当您实际传递方法并在
StartAsyncCommand
内部调用它时,应该可以使用
eg. 例如。
public StartAsyncCommand(Func<Task> fnc) {...}
as constructor and then just executing the func when the actual command is used public StartAsyncCommand(Func<Task> fnc) {...}
作为构造函数,然后在使用实际命令时仅执行func
wondering why your visual studio is not displaying you some "this method is not awaited" info message though .. 想知道为什么您的视觉工作室没有向您显示一些“未等待此方法”的信息消息..
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.