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类. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |