Accessing a property in one ViewModel from another

前端 未结 1 1124
伪装坚强ぢ
伪装坚强ぢ 2020-12-06 02:38

I want main viewmodel to have a certain list, and then access from many other viewmodels.

For example, in MainViewModel.cs I will have a list of 50 numbers, then in

相关标签:
1条回答
  • 2020-12-06 03:16

    If you want direct access to the list from an external ViewModel, then your options are to:

    1. Pass the List to the OtherVM as a constructor argument or public property. Then the OtherVM can treat it like a member.

    2. Pass the MainVM to the OtherVM as a constructor argument or public property. Then the OtherVM can access the List by first accessing the MainVM.

    3. Give the MainVM a static property called "Default" or "Instance," so you can access the static instance of MainVM from within OtherVM, without assigning it as a member field.

    Example:

    public class MainVM
    {
        private static MainVM _instance = new MainVM();
        public static MainVM Instance { get { return _instance; } }
    
        public List<XX> MyList { get; set; }
        //other stuff here
    }
    
    //From within OtherVM:
    MainVM.Instance.MyList.Add(stuff);
    
    0 讨论(0)
提交回复
热议问题