简体   繁体   中英

How to resolve System.Reflection.TargetInvocationException' error?

I'm using the MVVM Light libraries in my application which provides an Ioc container, called the ViewModelLocator. But when I set up a second property in the locator for a new View Model, I get a System.Reflection.TargetInvocationException

I debugged this by looking at the inner exception, and it seems that this error is thrown as I didn't specify that a parameter is being passed into the other VM, in my locator.

Does anyone know how I can set up my ViewSubjectGradeViewModel property in the locator class to account for the ScoreModel parameter that is passed into that model?

This is the ViewModelLocator for reference:

namespace LC_Points.ViewModel
{
    /// <summary>
    /// This class contains static references to all the view models in the
    /// application and provides an entry point for the bindings.
    /// </summary>
    public class ViewModelLocator
    {
        public ViewModelLocator()
        {
            ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);

            SimpleIoc.Default.Register<MainViewModel>();
            SimpleIoc.Default.Register<ViewSubjectGradeViewModel>();    
        }

        public MainViewModel MainPage
        {
            get { return ServiceLocator.Current.GetInstance<MainViewModel>(); }
        }

        public ViewSubjectGradeViewModel ViewSubjectGradePage
        {
            get { return ServiceLocator.Current.GetInstance<ViewSubjectGradeViewModel>(); }
        }

        public static void Cleanup()
        {
            // TODO Clear the ViewModels
        }
    }
}

And this is the new VM that I want to set a property for in the locator class:

namespace LC_Points.ViewModel
{
    public class ViewSubjectGradeViewModel 
    {
        public ViewSubjectGradeViewModel(IEnumerable<ScoreModel> addedSubjectGradePairs)
        {
            this.AddedSubjectGradePairsCopy = addedSubjectGradePairs;           
        }

        //Property for collection passed from MainViewModel
        public IEnumerable<ScoreModel> AddedSubjectGradePairsCopy { get; set; }         
    }
}

you don't have a default constructor.

In C#, whenever you specify a constructor that takes arguments your default constructor (empty constructor) is taken away. You can either specify a default constructor ( public ViewSubjectGradeViewModel(){} ) or tell service locator how to instantiate your object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM