如何使用 C# 阻止按钮在 Xamarin.Forms 中执行绑定命令?

How do I stop a button from executing a bound command in Xamarin.Forms using C#?

我创建了一个在“编辑”和“保存”之间切换的按钮。此按钮具有到我的 ViewModel 中的“保存命令”的数据绑定。

我想停止执行“保存命令”,直到按钮文本等于“保存”为止。

我试过切换 Command.CanExceute(false) 但这似乎不起作用,无论如何“保存命令”总是执行!示例代码发布在下面,也可以在我的 GitHub Repositry

中找到

MainPage.xaml

    <ContentPage.BindingContext>
        <App:ClientViewModel/>
    </ContentPage.BindingContext>
    
    <StackLayout>
        <Button x:Name="EditSaveButton"
                Text="Edit"
                Command="{Binding SaveClient}"
                Clicked="EditSaveButton_Clicked"/>
    </StackLayout>

MainPage.xaml.cs

        public MainPage()
        {
            InitializeComponent();
            EditSaveButton.Command.CanExecute(false);
        }

        private void EditSaveButton_Clicked(object sender, EventArgs e)
        {
            if (EditSaveButton.Text == "Edit")
            {
                EditSaveButton.Text = "Save";
                EditSaveButton.Command.CanExecute(true);
            }
            else 
            {
                EditSaveButton.Text = "Edit";
                EditSaveButton.Command.CanExecute(false);
            }
        }

ClientViewModel.cs

    public class ClientViewModel
    {
        public Command SaveClient { get; set; }

        public ClientViewModel()
        {
            SaveClient = new Command( async () => {

                await Application.Current.MainPage.DisplayAlert("Saved", "Client Saved", "OK");
            });
        }
    }

######更新######

感谢 Jason 和 Robert Harvey 对此的指导。 我已将我的代码更改为仅使用 Command 而不是 Clicked,并将按钮的文本 属性 绑定到我的 ViewModel 中的 属性。但是,当我执行代码时,按钮文本没有更新?有什么想法吗?

Main.xaml

    <StackLayout>
        <Button x:Name="EditSaveButton"
                Text="{Binding EditSaveButtonText}"
                Command="{Binding SaveClient}"/>
    </StackLayout>

ClientViewModel.cs

 public class ClientViewModel
    {
        public Command SaveClient { get; set; }

        public string EditSaveButtonText { get; set; }

        public ClientViewModel()
        {

            SaveClient = new Command( () => {

                if (EditSaveButtonText == "Edit")
                {
                    EditSaveButtonText = "Save";
                }
                else
                {
                    EditSaveButtonText = "Edit";
                }
            });
        }
    }

Xamarin 中的命令实现了 ICommand 接口。

public interface ICommand
{
    public void Execute (Object parameter);

    public bool CanExecute (Object parameter);

    public event EventHandler CanExecuteChanged;
}

如果您将按钮中的命令绑定到实现 ICommand 的视图模型,只需将 CanExecute 设置为 false您应该在视图模型而不是视图中执行此操作。

将事件绑定到按钮或使用 Command不要两者都做。如果您需要更改按钮颜色,请将按钮颜色设置为视图模型的 属性 绑定,以便您可以更改它那里。