Xamarin中MVVM Light的RelayCommand失效,请求排查解决
解决MVVM Light RelayCommand按钮无响应的问题
嘿,我帮你排查下代码里的几个关键问题,这些大概率是导致按钮点击没反应的原因:
1. 页面没绑定ViewModel实例
你的XAML里把按钮命令绑定到了ConvertCommand,但如果页面的BindingContext没设置成MainViewModel的实例,绑定系统根本找不到这个命令。这是最常见的坑!
修复方式:打开页面的代码后台(比如MainPage.xaml.cs),在构造函数里加上这行:
public MainPage() { InitializeComponent(); // 把ViewModel实例赋值给BindingContext BindingContext = new MainViewModel(); }
2. ViewModel可以继承ViewModelBase(推荐)
虽然不是强制要求,但MVVM Light的ViewModelBase帮你实现了INotifyPropertyChanged接口,后续要是需要更新UI元素,继承它会省很多事。修改你的ViewModel:
using GalaSoft.MvvmLight; // 别忘了引用这个命名空间 public class MainViewModel : ViewModelBase { // 你的原有代码可以保留,只是加个继承 }
3. RelayCommand的定义可以优化下
你现在每次访问ConvertCommand都会新建一个RelayCommand实例,虽然功能上能跑,但更规范的写法是只初始化一次,避免不必要的对象创建:
private ICommand _convertCommand; public ICommand ConvertCommand { get { return _convertCommand ?? (_convertCommand = new RelayCommand(ConvertMoney)); } }
4. 关于DisplayAlert的小提醒
确保App.Current.MainPage不是null就行,正常应用启动后主页面肯定是初始化好的,不过也可以换成Application.Current.MainPage,效果是一样的。
完整修复后的代码参考
MainViewModel.cs
using GalaSoft.MvvmLight; using GalaSoft.MvvmLight.Command; using System.Threading.Tasks; public class MainViewModel : ViewModelBase { private ICommand _convertCommand; public ICommand ConvertCommand { get { return _convertCommand ?? (_convertCommand = new RelayCommand(async () => await ConvertMoney())); } } public async Task ConvertMoney() { await Application.Current.MainPage.DisplayAlert("Hello", "终于弹出提示啦!", "Accept"); } }
MainPage.xaml.cs
public partial class MainPage : ContentPage { public MainPage() { InitializeComponent(); BindingContext = new MainViewModel(); } }
你的XAML代码没问题,直接用就行:
<StackLayout Padding="8"> <Button Command="{Binding ConvertCommand}" Text="Hello" /> </StackLayout>
按照上面的步骤改完,点击按钮应该就能正常弹出提示框啦!
内容的提问来源于stack exchange,提问作者Armando Alvarez
相关产品推荐
相关产品推荐

