微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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类.

原文地址:https://www.jb51.cc/csharp/100965.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐