【问题标题】:Xamarin Command not firing on Button ClickXamarin 命令未在按钮单击时触发
【发布时间】:2018-10-05 14:15:53
【问题描述】:

我为测试目的制作了一个 Xamarin 应用程序,出于某种原因,我添加的按钮不会触发该命令。我也尝试过从代码隐藏和 xaml 设置上下文,但它仍然不起作用。

XAML 代码:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:implementation="clr-namespace:RxposTestApp.Implementation;assembly=RxposTestApp"
             x:Class="RxposTestApp.Page">
    <ContentPage.BindingContext>
        <implementation:BaseCommandHandler/>
    </ContentPage.BindingContext>
    <ContentPage.Content>
        <StackLayout>
            <Label Text="Welcome to Xamarin.Forms!"
                VerticalOptions="CenterAndExpand" 
                HorizontalOptions="CenterAndExpand" />
            <Button Text="CLIK MIE" Command="BaseCommand"/>
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

BaseCommandHandler 类:

public class BaseCommandHandler : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    public ICommand BaseCommand { get; set; }

    public BaseCommandHandler()
    {
        BaseCommand = new Command(HandleCommand);
    }



    public void HandleCommand()
    {
       //should fire this method
    }
}

【问题讨论】:

    标签: xamarin button command click


    【解决方案1】:

    所以问题是

    <Button Text="CLIK MIE" Command="BaseCommand"/>
    

    让我们退后一步,谈谈绑定。

    <Button Text="CLIK MIE" Command="{Binding BaseCommand}"/>
    

    您会注意到 {Binding ...},它告诉 XAML 引擎在绑定上下文中查找公共属性。在这种情况下,我们要查找名为“BaseCommand”的公共属性。绑定提供了很多东西。其中之一是监听属性更改通知。

    下一个问题是我们如何通知视图该命令可以执行?还是目前无法执行?或 BaseCommand 属性设置为 ICommand 实例而不是 null?

    我通常更喜欢使用私有字段来支持公共属性。

    private ICommand _baseCommand;
    Public ICommand BaseCommand
    {
        get
           {
               return this._baseCommand;
           }
        set
           {
               this._baseCommand = value;
               // Notification for the view. 
           }
    }
    

    通过这种方式,您可以根据自己的喜好发出通知,并且当 BaseCommand 的值发生变化时,它总是会发出。

    【讨论】:

      【解决方案2】:
      <Button Text="CLIK MIE" Command="{Binding BaseCommand}"/>
      

      您正在使用 MVVM,因此您需要将您的属性从 ViewModel 绑定到您的 View。

      【讨论】:

      • 您能说得更具体一点吗?我认为创建一个具有 ICommand 属性的类然后简单地绑定它的上下文就足够了。类的名称是否必须以 ViewModel 结尾,或者我到底错过了什么?
      • 这是声明绑定上下文的地方。您将 BaseCommandHandler 设置为您的 ViewModel。在这种情况下,您应该使用“绑定”将该模型(类)中的所有属性绑定到您的 XAML。我建议您阅读一些有关 MVVM 的内容,以熟悉某个主题。
      猜你喜欢
      • 2012-01-15
      • 2014-02-16
      • 2018-03-02
      • 2011-09-30
      • 2020-03-26
      • 2014-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多