使用MvvmCross和Xamarin.Forms简单处理ICommand时遇到问题。
我用VisualStudio的MvvmCross插件创建了一个项目,我有简单的MainView.xaml和MainViewModel.cs
我更改了ViewModel :(只添加了一个字符串+一个ICommand)
using System.Diagnostics;
using System.Windows.Input;
using Cirrious.MvvmCross.ViewModels;
namespace XamarinFormsMvvm.Core.ViewModels
{
public class MainViewModel : BaseViewModel
{
private string sampleText = "Hello from the Ninja Coder!";
private string sampleText2 = "Hello2";
public MainViewModel()
{
}
public string SampleText
{
get { return this.sampleText; }
set { this.SetProperty(ref this.sampleText, value); }
}
public string SampleText2
{
get { return this.sampleText2; }
set { this.SetProperty(ref this.sampleText2, value); }
}
public ICommand StartStopCommand
{
get
{
return new MvxCommand(() =>
{
Debug.WriteLine("Test");
});
}
}
}
}
我的观点(添加标签+按钮)
<?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="XamarinFormsMvvm.Forms.Views.MainView"
xmlns:viewModels="clr-namespace:XamarinFormsMvvm.Core.ViewModels;assembly=XamarinFormsMvvm.Core"
Title="MainView Page"
>
<ContentPage.BindingContext>
<viewModels:MainViewModel />
</ContentPage.BindingContext>
<ContentView>
<StackLayout>
<Label Text='{Binding SampleText}' VerticalOptions='Center' HorizontalOptions='Center'/>
<Label Text='{Binding SampleText2}' VerticalOptions='Center' HorizontalOptions='Center'/>
<Button Command="{Binding StartStopCommand}" Text="asd" VerticalOptions="Center" HorizontalOptions="Center"/>
</StackLayout>
</ContentView>
</ContentPage>
在跑完之后我得到例外:
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.NullReferenceException: Object reference not set to an instance of an object
03-05 18:32:16.898 I/MonoDroid( 2699): at Cirrious.CrossCore.Mvx.TryResolve[IMvxCommandHelper] (IMvxCommandHelper& service) [0x00000] in <filename unknown>:0
03-05 18:32:16.898 I/MonoDroid( 2699): at Cirrious.MvvmCross.ViewModels.MvxCommandBase..ctor () [0x00000] in <filename unknown>:0
03-05 18:32:16.898 I/MonoDroid( 2699): at Cirrious.MvvmCross.ViewModels.MvxCommand..ctor (System.Action execute, System.Func`1 canExecute) [0x00000] in <filename unknown>:0
03-05 18:32:16.898 I/MonoDroid( 2699): at Cirrious.MvvmCross.ViewModels.MvxCommand..ctor (System.Action execute) [0x00000] in <filename unknown>:0
03-05 18:32:16.898 I/MonoDroid( 2699): at XamarinFormsMvvm.Core.ViewModels.MainViewModel.get_StartStopCommand () [0x00001] in c:\Users\Tomasz\Documents\Visual Studio 2013\Projects\XamarinFormsMvvm\XamarinFormsMvvm.Core\ViewModels\MainViewModel.cs:49
...........
此代码有什么问题?
答案 0 :(得分:0)
我刚刚和Ninja一起创建了一个项目,并在MainViewModel&amp; MainView和一切都很棒。 说实话,我不得不说在Ninja创建之后我修改了一些解决方案结构。
你可以找到我修改过的NinjaMvxForms空白项目&amp;在这里工作https://github.com/MobiliTips/NinjaMvxForms