首先,命令是 MVVM 模式的一部分,您应该首先了解它。
C# 中的接口不提供任何功能,它们只描述继承该接口的类应该如何工作。如果你想让类做某事,你不应该把这些方法留空。
WPF 中的命令代表一种框架,稍后将向其传输逻辑。命令最合乎逻辑的用法是将它们绑定到按钮。
ICommand 实现示例:
public class RelayCommand : ICommand
{
private readonly Action<object> execute;
private readonly Func<object, bool> canExecute;
public event EventHandler CanExecuteChanged {
add => CommandManager.RequerySuggested += value;
remove => CommandManager.RequerySuggested -= value;
}
public RelayCommand(Action<object> execute, Func<object, bool> canExecute = null)
{
this.execute = execute;
this.canExecute = canExecute;
}
public bool CanExecute(object parameter)
{
return canExecute == null || canExecute(parameter);
}
public void Execute(object parameter)
{
execute(parameter);
}
}
命令使用示例:
public static RelayCommand NavigateToSignInPage => new RelayCommand(
actionParameter => Application.Instance.Navigation.NavigateTo(new LoginForm()));
public static RelayCommand NavigateToSignUpPage => new RelayCommand(
actionParameter => Application.Instance.Navigation.NavigateTo(new RegistrationForm()));
public static RelayCommand NavigateToStartPage => new RelayCommand(
actionParameter => Application.Instance.Navigation.NavigateTo(new StartPage()));
public static RelayCommand NavigateBack => new RelayCommand(
actionParameter => Application.Instance.Navigation.NavigateBack(),
actionPossibilityParameter => Application.Instance.Navigation.BackNavigationPossible);
命令绑定示例:
在视图中 (xaml):
<Button x:Name="CancelButton"
Content="Cancel"
Command="{Binding CancelCommand}"
Grid.Row="2"
IsCancel="True"
HorizontalAlignment="Left"
Margin="44,0,0,0"
Width="118" Height="23"
VerticalAlignment="Center" />
在 ViewModel 中:
public RelayCommand CancelCommand => NavigationCommands.NavigateBack;