locked
How to get data from another viewmodel RRS feed

  • Question

  • hi all,

                    if there is a List<string>(Students) in Viewmodel A and some buttons(Teach Chinese/English...) in Viewmodel B.

    Now i want to get the 'Students' then do something when user click the button in Viewmodel B.

    what is the proper design to do this under MVVM architecture.

    it seems not a good way via Event/Mediator pattern. I just want to get the latest data when user do a click action.

    Monday, May 30, 2016 10:13 AM

Answers

  • If you just want to share the data then put a reference to it in application.current.resources.

    Application.Current.Resources.Add("myKey", MyObject);

    And get it back out:

     var BackOut = Application.Current.Resources["myKey"] as Whatever;


    Hope that helps.

    Technet articles: WPF: Layout Lab; All my Technet Articles

    • Proposed as answer by Weiwei Cai Monday, June 6, 2016 7:46 AM
    • Marked as answer by Weiwei Cai Tuesday, June 7, 2016 2:20 AM
    Tuesday, May 31, 2016 1:43 PM

All replies

  • Do your viewmodels really need to know when the value changes?

    You could use application.current.resources to store your property in a class which notifies property changed when your value is changed.

    or

    You could use mvvm light messenger.

    http://social.technet.microsoft.com/wiki/contents/articles/26070.communicating-between-classes.aspx


    Hope that helps.

    Technet articles: WPF: Layout Lab; All my Technet Articles

    Monday, May 30, 2016 3:20 PM
  • What i want is not when the value changes.

    I just want to get another viewmodel's data when i need it.

    Event-trigger/mediator pattern keep getting the changed data even another viewmodel doesn't need it at that time.

    I can implement it via passing a viewmodel's instance to another viewmodel / creating a singleton viewmodelManager to handle it, but i think these ways may not match MVVM.


    • Edited by 海獅 Tuesday, May 31, 2016 2:25 AM
    Tuesday, May 31, 2016 2:25 AM
  • If you just want to share the data then put a reference to it in application.current.resources.

    Application.Current.Resources.Add("myKey", MyObject);

    And get it back out:

     var BackOut = Application.Current.Resources["myKey"] as Whatever;


    Hope that helps.

    Technet articles: WPF: Layout Lab; All my Technet Articles

    • Proposed as answer by Weiwei Cai Monday, June 6, 2016 7:46 AM
    • Marked as answer by Weiwei Cai Tuesday, June 7, 2016 2:20 AM
    Tuesday, May 31, 2016 1:43 PM