按钮命令绑定在 Xamarin.Forms 中不起作用

本文关键字:Forms 不起作用 Xamarin 命令 绑定 按钮 | 更新日期: 2023-09-27 18:34:06

我想将命令绑定到按钮的命令属性。这似乎很简单,因为我以前在 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 类以防万一:

视图模型库

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"} );

这应该不会影响任何事情,但以防万一。那么我的命令绑定有什么问题呢?提前谢谢你!

按钮命令绑定在 Xamarin.Forms 中不起作用

这个答案与原始问题的问题没有直接关系,但是这个问题是搜索引擎中排名最高的问题,这个问题的标题与这个答案回答的问题模棱两可。

我在使用不会触发相关命令操作的Command时遇到问题。我的问题是我将Command定义为field而不是property

工程:

public Command MyCommand { get; set; }

不起作用:

public Command MyCommand;

希望这对其他人有所帮助。

你快到了。仔细查看您对 OnPropertyChanged 方法的调用;您传递的是数字文本的值,而不是名称。如果您更改代码以传递"数字文本",我希望它能正常工作。

编辑:我应该补充一点,构造函数中的 OnPropertyChanged 调用也有同样的问题。在启动时看到"0"的原因是视图只是使用现有绑定来检索值。

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