【问题标题】:Xamarin RelayCommand doesn't workXamarin RelayCommand 不起作用
【发布时间】:2018-05-31 18:21:32
【问题描述】:

我有一个使用 MVVM Light nuget 的 RelayCommand 的简单代码,但无法正常工作,只想按一个按钮并显示一条消息,

我的 xaml 代码:

 <StackLayout
  Padding="8">
    <Button

        Command="{Binding ConvertCommand}"

        Text="Hello">
    </Button>
</StackLayout>

我的视图模型:

public class MainViewModel
{
    public ICommand ConvertCommand { get { return new RelayCommand(ConvertMoney); } }

    public async void ConvertMoney()
    {
        await App.Current.MainPage.DisplayAlert("hello", "hello", "acept");
        return;
    }

}

【问题讨论】:

  • 您是否设置了视图的绑定上下文?也不要将 async 与 void 一起使用,而是使用 Task。
  • 绑定工作正常,使用Command代替RelayCommand效果很好,谢谢你的cmets!!!

标签: xamarin.forms mvvm-light


【解决方案1】:

我认为您缺少将您的PageStackLayoutBindingContext 设置为您的ViewModel

例如

<ContentPage.BindingContext>
    <viewModels:MainViewModel/>
</ContentPage.BindingContext>

<StackLayout.BindingContext>
    <viewModels:MainViewModel/>
</StackLayout.BindingContext>

顺便说一下,您不需要将MvvmLight 添加到您的Xamarin.Forms 项目中,因为Xamarin.Forms 有自己的ICommand 实现。你可以简单地使用Command

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-19
    • 1970-01-01
    • 1970-01-01
    • 2015-10-27
    • 2020-12-08
    • 2017-05-10
    • 1970-01-01
    相关资源
    最近更新 更多