【问题标题】:MVVM Light IoC not Binding? What am I missing?MVVM Light IoC 未绑定?我错过了什么?
【发布时间】:2013-07-16 16:19:27
【问题描述】:

我正在开发一个 Windows 7 手机应用程序。我创建了几个带有接口的服务类,但每次我尝试导航这些视图时,它们现在都会崩溃。

我将我的项目设置为在模拟器加载后立即加载其中一个视图(通过 WMAppManifest.xml)

我有这样的事情

 public interface IGpsService
    {
        void StartGps();
        GeoPosition<GeoCoordinate> CurrentPostion();
    }


public class GpsService : IGpsService
{
    private GeoCoordinateWatcher gpsWatcher;

    public GpsService()
    {
        gpsWatcher = new GeoCoordinateWatcher(GeoPositionAccuracy.Default)
        {
            MovementThreshold = 20,
        };

    }

    public void StartGps()
    {
        gpsWatcher.Start();
    }

    public GeoPosition<GeoCoordinate> CurrentPostion()
    {
        return gpsWatcher.Position;
    }

}

我的视图模型定位器

   static ViewModelLocator()
    {
        ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);

        if (ViewModelBase.IsInDesignModeStatic)
        {
            SimpleIoc.Default.Register<IGpsService, Design.GpsDataService>();
        }
        else
        {
            SimpleIoc.Default.Register<IGpsService, GpsService>();
        }
        SimpleIoc.Default.Register<AddProductPriceVm>();
    }

// AddProductPrice.xaml.cs

 public AddProductPrice(IGpsService gpsService)
    {
        InitializeComponent();
    }

Ioc 是否只绑定到视图模型或其他东西?这就是为什么它不能像我在我的代码中那样工作的原因吗?

我混合使用了 code behind 和 MVVM,因为使用 code behind 更容易做到。

错误信息

MissingMethodException
   at System.Activator.InternalCreateInstance(Type type, Boolean nonPublic, StackCrawlMark& stackMark)
   at System.Activator.CreateInstance(Type type)
   at System.Windows.Navigation.PageResourceContentLoader.BeginLoad_OnUIThread(AsyncCallback userCallback, PageResourceContentLoaderAsyncResult result)
   at System.Windows.Navigation.PageResourceContentLoader.<>c__DisplayClass4.<BeginLoad>b__0(Object args)
   at System.Reflection.RuntimeMethodInfo.InternalInvoke(RuntimeMethodInfo rtmi, Object obj, BindingFlags invokeAttr, Binder binder, Object parameters, CultureInfo culture, Boolean isBinderDefault, Assembly caller, Boolean verifyAccess, StackCrawlMark& stackMark)
   at System.Reflection.RuntimeMethodInfo.InternalInvoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, StackCrawlMark& stackMark)
   at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
   at System.Delegate.DynamicInvokeOne(Object[] args)
   at System.MulticastDelegate.DynamicInvokeImpl(Object[] args)
   at System.Delegate.DynamicInvoke(Object[] args)
   at System.Windows.Threading.DispatcherOperation.Invoke()
   at System.Windows.Threading.Dispatcher.Dispatch(DispatcherPriority priority)
   at System.Windows.Threading.Dispatcher.OnInvoke(Object context)
   at System.Windows.Hosting.CallbackCookie.Invoke(Object[] args)
   at System.Windows.Hosting.DelegateWrapper.InternalInvoke(Object[] args)
   at System.Windows.RuntimeHost.ManagedHost.InvokeDelegate(IntPtr pHandle, Int32 nParamCount, ScriptParam[] pParams, ScriptParam& pResult)

导航失败

   // Code to execute if a navigation fails
    private void RootFrame_NavigationFailed(object sender, NavigationFailedEventArgs e)
    {
        if (System.Diagnostics.Debugger.IsAttached)
        {
            // A navigation has failed; break into the debugger
            System.Diagnostics.Debugger.Break();
        }
    }

【问题讨论】:

  • 错误信息是什么?
  • Opps 忘记发了。现在完成。

标签: windows-phone-7 mvvm inversion-of-control mvvm-light


【解决方案1】:

您将服务直接注入视图,而不是视图模型。视图不是使用 SimpleIoc 创建的,因此不知道在构造函数中解析 IGpsService 引用的位置。

如果您想这样做,最好的选择是将 IGpsService 注入您的视图模型并将其作为属性公开。将 DataContextChanged 事件添加到您的视图中,并在它触发时从视图模型中获取 IGpsService。

编辑:

//添加产品价格查看

<UserControl
DataContext="{StaticResource  Locator.AddProductPriceVm}">

/AddProductPrice.xaml.cs

public AddProductPrice()
    {
        InitializeComponent();
        DataContextChanged+=DataContextChanged
    }
        void DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            var context=sender as AddProductPriceVm;
            if(context!=null)
                _myGpsService=context.GpsService;
        }

//AddProductPriceVm

public class AddProductPriceVm
{
public AddProductPriceVm(IGpsService gpsService)
{
   GpsService=gpsService;
}
public IGpsService GpsService{get;set;}
}

这个问题并不是真正的 DI 问题,而是 MVVM Light 的工作原理。它期望视图在执行和依赖注入之前就在那里。如果你想将东西直接注入到视图中,那么你可以考虑使用 Prism(但它更重,有更多的脚手架)。

【讨论】:

  • 您能举个例子吗?所有的 Ioc 也会遇到同样的问题吗?
  • hmm 所以切换到 Nnject 不会解决任何问题。 MVVM 灯是如何设计的。我猜你展示的是推荐的传递服务的方式?假设如果多个 VM 需要相同的服务,它们会共享同一个实例还是都具有不同的实例?
猜你喜欢
  • 2015-08-06
  • 2011-08-31
  • 2023-03-15
  • 2012-04-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多