如何在没有 MVVM 框架的情况下在通用 Windows 平台中创建参数化命令?我试图实现 RelayCommand 类,但 System.Windows.Input 命名空间没有 CommandManager 类.
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.
推荐答案如果不想使用框架,则必须自己实现接口System.Windows.Input.ICommand.
If you don't want to use a framework, you have to implement the interface System.Windows.Input.ICommand yourself.
命令参数可以通过属性CommandParameter 传递.不需要命令管理器.如果您对参数使用单向绑定,则当绑定更改时,按钮将自动启用/禁用.对于任何其他引发事件 CanExecuteChanged.
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.
简化示例
这里是一个如何使用带有 x:Bind 绑定的按钮的简化示例.不需要视图模型或命令管理器.
Here a simplified example how to use a button with x:Bind binding. No view model or command manager is reuired.
示例.xaml:
<Button x:Name="Test" Command="{x:Bind FirstCommand}" CommandParameter="{x:Bind SelectedItem, Mode=OneWay"> <TextBlock>Test</TextBlock> </Button>示例.xaml.cs:
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:
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)) //... } }更多推荐
带参数的通用 Windows 平台命令
发布评论