Xamarin Forms MvvmCross绑定按钮命令错误

时间:2019-03-08 14:49:10

标签: xamarin button command mvvmcross

我正在研究Xamarin Forms MvvmCross项目。我将视图模型上的通用按钮命令与视图模型上的IMvxAsyncCommand绑定在一起,如下所示:

  • 查看

    <views:MvxContentPage xmlns="http://xamarin.com/schemas/2014/forms"
                      xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                      xmlns:views="clr- namespace:MvvmCross.Forms.Views;assembly=MvvmCross.Forms"
                      x:Class="TestProject.Pages.TestPage">
    <ContentView>
        <StackLayout>
            <Button Text="Test the command!" Command="{Binding TestAsyncCommand}"/>
        </StackLayout>
    </ContentView>
    

  • 查看模型

    namespace TestProject.ViewModels
    {
        public class TestViewModel : MvxNavigationViewModel
        {
            public TestViewModel(IMvxLogProvider logProvider, IMvxNavigationService navigationService)
                : base(logProvider, navigation)
            {
            }
    
            public IMvxAsyncCommand TestAsyncCommand => new MvxAsyncCommand(async () => await TestAsyncCommandMethod());
    
            private async Task TestAsyncCommandMethod()
            {
                //await some stuff
            }
        }
    }
    

任何事情似乎都可以正常工作,但很少在按下按钮后变为禁用状态。会发生什么?如果我使用Command代替MvxAsyncCommand,似乎没有发生(但我不确定),如下所示:

public Command TestAsyncCommand => new Command(async () => await TestAsyncCommandMethod());

注意:TestAsyncCommandMethod完全封装在try-catch块中,以避免可能的异常。

1 个答案:

答案 0 :(得分:0)

我认为您在这里做错的是,不是创建一个属性来绑定View和ViewModel,而是使用字段,您可以尝试以下操作:

public IMvxAsyncCommand TestAsyncCommand {get; set;}

然后在构造函数中执行以下操作:

public TestViewModel(IMvxLogProvider logProvider, IMvxNavigationService navigationService)
        : base(logProvider, navigation)
    {
      TestAsyncCommand = new MvxAsyncCommand(async () => await TestAsyncCommandMethod());
    }

更新

这似乎是MvvmCross的错误! 可以在添加的链接中找到问题

https://github.com/MvvmCross/MvvmCross/issues/1589