Skip to content

MAUI 数据绑定之命令绑定

L edited this page Mar 25, 2023 · 1 revision

MAUI中的命令绑定模式可以将控件的行为与命令相关联,使得在触发控件的行为时能够执行特定的命令逻辑。这种模式适用于需要将控件的行为与特定逻辑相关联的情况,例如当用户点击一个按钮时需要执行一个命令,或者当用户在文本框中输入完毕后需要执行一个验证命令等。
一般来说,命令绑定模式常用于以下场景:
当需要将控件行为与特定逻辑相关联时,例如验证、保存、执行操作等。
当需要通过单个命令来处理多个控件的行为时,例如批量处理、表单提交等。
当需要将行为的执行结果反馈给控件时,例如刷新、禁用/启用等。

下面是一个 MAUI 命令绑定的例子,一个按钮可以调用一个简单的命令来显示一个弹出框。

<StackLayout>
    <Button Text="Click Me" Command="{Binding ShowAlertCommand}" />
</StackLayout>

在后端代码中,我们需要创建一个名为 ShowAlertCommand 的命令对象,并定义 Execute 方法和 CanExecute 方法。
这里 CanExecute 始终返回 true,因此该命令始终可执行:

public partial class CommandBindingPage : ContentPage
{
    public ICommand ShowAlertCommand { get; set; }
    public CommandBindingPage()
    {
        InitializeComponent();

        ShowAlertCommand = new Command(() =>
        {
            DisplayAlert("Alert", "You clicked the button!", "OK");
        }, () => true);

        BindingContext = this;
    }
}

这里我们在创建 ShowAlertCommand 对象的时候,使用了下面的构造函数,定义了 Execute 方法和 CanExecute 方法。CanExecute 始终返回 true,因此该命令始终可执行:

public Command(Action execute, Func<bool> canExecute);

当用户单击按钮时,将调用命令的 Execute 方法并显示一个弹出框。
效果如图:
9

示例代码

CommandBindingPage.xaml
CommandBindingPage.xaml.cs

参考资料

基本绑定

Clone this wiki locally