c# – Button命令绑定在Xamarin.Forms中不起作用

我想将命令绑定到我的按钮的command属性.这似乎非常简单,因为我之前在 WPF中已经多次这样做了,这里的方法非常相似.让我展示一些代码片段.

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" 
         x:Class="MyApp.View.CustomPage"
         Title="Something">

<ContentPage.Content>
    <StackLayout>
        <Button x:Name="numBtn" Text="Increase number" Command="{Binding IncreaseCommand}" />
        <Label x:Name="numLabel" Text="{Binding numberText}" />
    </StackLayout>
</ContentPage.Content>
</ContentPage>

代码隐藏

public partial class CustomPage : ContentPage
{   
    public CustomPage ()
    {
        InitializeComponent ();
        BindingContext = viewmodelLocator.viewmodel();  //viewmodelLocator is singleton,gives
                                                        //you a viewmodel instance
    }
}

视图模型

public ICommand IncreaseCommand { get; private set; }
private int number;
public string numberText { get; private set;}

构造函数

public viewmodel()
{
    IncreaseCommand = new Command (() => IncreaseExecuted ());
    number = 0;
    numberText = number.ToString ();
    OnPropertyChanged (numberText);
}

然后

private void IncreaseExecuted()
{
    number++;
    numberText = number.ToString ();
    OnPropertyChanged (numberText);
}

当我使用Xamarin Android Player(KitKat)运行应用程序时,我看到按钮,标签读数为0.然后我按下按钮,没有任何反应.我尝试检查断点会发生什么,但应用程序不会暂停,即使它们在我的viewmodel的构造函数中也没有.我想这与模拟器有关.无论如何,我认为绑定是好的,因为我可以在屏幕上看到“0”.可能是什么问题呢?让我展示我的viewmodelBase类以防万一:

viewmodelBase

public abstract class viewmodelBase : INotifyPropertyChanged
{

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(String propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this,new PropertyChangedEventArgs(propertyName));
        }
    }
}

当我调用OnPropertyChanged时,我的numberText属性可能没有更新?但我以前曾多次使用过完全相同的viewmodelBase类,但它总能正常工作.最后一件事,我的CustomPage页面被包装在一个NavigationPage中,它是TabbedPage的子节点:

MainPage.xaml.cs中

this.Children.Add (new NavigationPage (new CustomPage ()) {Title="Something"} );

这不应该影响任何东西,但只是以防万一.那我的命令绑定有什么问题?先感谢您!

解决方法

你快到了.仔细查看对OnPropertyChanged方法调用;您传递的是numberText的值,而不是名称.如果您更改代码以传递“numberText”,我希望它能够正常工作.

编辑:我应该补充说,构造函数中的OnPropertyChanged调用具有相同的问题.您在启动时看到“0”的原因是视图只是使用现有绑定来检索值.

编辑2:现在Xamarin支持C#6.0,您可以使用新的“nameof”表达式,无需使用硬编码字符串.或者,您可以使用MvvmCross,MvvmLight或XLabs的MVVM类.

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...