使用类参考MVVM光中的视图模型定位器

时间:2016-12-27 06:04:53

标签: c# xamarin.forms mvvm-light

我正在尝试使用代码来查找视图模型定位器的引用,但是我收到一条错误,指出对象引用不能设置为对象的实例: -

internal class Locator : ViewModelLocator
{
    private static readonly Lazy<Locator> _locator = new Lazy<Locator>(() => new Locator(), LazyThreadSafetyMode.PublicationOnly);
    public static Locator Instance => _locator.Value;
    private Locator()
    {
        SimpleIoc.Default.Register<MainViewModel>();
        SimpleIoc.Default.Register<AddStudentViewModel>();
    }
 }

任何人都可以帮助我解决这个问题吗?

3 个答案:

答案 0 :(得分:2)

我在项目中使用波纹管代码,你需要添加public get set属性来定位你在locator类中的视图模型: -

 internal class Locator : ViewModelLocator
        {
            private static readonly Lazy<Locator> _locator = new Lazy<Locator>(() => new Locator(), LazyThreadSafetyMode.PublicationOnly);
            public static Locator Instance => _locator.Value;

            private Locator()
            {
                SimpleIoc.Default.Register<MainViewModel>();
                SimpleIoc.Default.Register<AddStudentViewModel>();

            }

            public MainViewModel Main
            {
                get
                {
                    return ServiceLocator.Current.GetInstance<MainViewModel>();
                }
            }
            public AddStudentViewModel AddStudentViewModel
            {
                get
                {
                    return ServiceLocator.Current.GetInstance<QuestionsViewModel>();
                }
            }

        } 

或者实现相同的另一种方式如下: - 你可以在app.cs中创建一个定位器的get set属性: -

 public static ViewModelLocator Locator
        {
            get { return _locator ?? new ViewModelLocator(); }
        }

答案 1 :(得分:1)

我更喜欢你通过延迟加载的第一种方法,你可以找到你的定位器的参考:)

 import React, {Compoment} from 'react';
    import ReactDOM from 'react-dom';
    class App extends React.Compoment {
        constructor(props){
            super(props);
            this.handleClick = this.handleClick.bind(this);
        }
        handleClick(){
            if(this.myTextInput !=null) {
                this.myTextInput.focus();
            }
        }
        render (){
            return (
                <div>
                    <input type="text" ref={(ref) => this.myTextInput = ref} />
                    <input type="button"
                        value="'Focus the text input"
                           onClick={this.handleClick}
                    />
                </div>
            );
        }
    }
    ReactDOM.render(<App />, document.getElementById('app'));

答案 2 :(得分:0)

注册viewmodel后需要创建这样的方法

    public CreateAssetViewModel CreateAssetVM
    {
        get
        {
            if (!SimpleIoc.Default.IsRegistered<CreateAssetViewModel>())
            {
                SimpleIoc.Default.Register<CreateAssetViewModel>();
            }
            return ServiceLocator.Current.GetInstance<CreateAssetViewModel>();
        }
    }