问题
How I can make parameterized commands in Universal Windows Platform without MVVM-frameworks? I was tried to implement RelayCommand class, but System.Windows.Input namespace haven't CommandManager class.
回答1:
If you don't want to use a framework, you have to implement the interface System.Windows.Input.ICommand
yourself.
Command parameters can be passed by the the property CommandParameter
. There is no need for a command manager. If you use a one-way binding for the parameter, the button will be enabled / disabled automatically when the binding change. For anything else raise the event CanExecuteChanged
.
Of course, in a more advanced scenario, you'll have to implement some state management for the command as well, which is easier if the commands are defined in a viewmodel or use are using some kind of self implemented command manager.
Simplified example
Here a simplified example how to use a button with x:Bind
binding. No view model or command manager is reuired.
Example.xaml:
<Button x:Name="Test" Command="{x:Bind FirstCommand}" CommandParameter="{x:Bind SelectedItem, Mode=OneWay">
<TextBlock>Test</TextBlock>
</Button>
Example.xaml.cs:
public sealed partial class Example : Page {
public SampleCommand FirstCommand { get; set; } =
new SampleCommand();
public object SelectedItem { get; set; }
public StandardProjectList() {
this.InitializeComponent();
}
}
SampleCommand.cs:
public class SampleCommand : ICommand {
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter) {
return parameter != null;
}
public void Execute(object parameter) {
if (CanExecute(parameter))
//...
}
}
来源:https://stackoverflow.com/questions/33003207/universal-windows-platform-commanding-with-parameters