Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. WPF
  4. How to pass a new instance of a viewmodel to an existing usercontrol?

How to pass a new instance of a viewmodel to an existing usercontrol?

Scheduled Pinned Locked Moved WPF
questiondatabasetutorialannouncement
17 Posts 4 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • P Pete OHanlon

    Strictly speaking, you wouldn't pass the data in. The reason that this is a no-no is that you've introduced a coupling here where the parent ViewModel has to know what views are associated with it, and hence the ViewModels that are associated with those views. This is a real no-no. Remember that MVVM is based on the concept of a ViewModel wiring up to a Model; this tells you that your child VM needs to hook into the same data as the top-level VM. There's no real reason though, that this has to be a database. What you could do is have a top-level entity which is responsible for reading a whole bunch of data in that your top level VM uses, and your child VMs could also use this source of data.

    Forgive your enemies - it messes with their heads

    My blog | My articles | MoXAML PowerToys | Mole 2010 - debugging made easier - my favourite utility

    L Offline
    L Offline
    Lost User
    wrote on last edited by
    #6

    Pete O'Hanlon wrote:

    the parent ViewModel has to know what views are associated with it, and hence the ViewModels that are associated with those views. This is a real no-no.

    I don't understand why you say this? Lets say I will have a page showing a list of customers, and also the individual fields from the currently selected customer. In MVVM I would create a VM for the page, and also (because the functionality is self-contained) a VM for the list of customers and a VM for the individual Customer fields (that is, ONE VM with properties for each Customer field) Now, my Page VM is nonsense without having a CustomerListVM and a CustomerEditVM somehow contained within it. It certainly doesn't know about the VIEWs but it MUST know about the ViewModels Similarly neither the customerListVM nor the CustomerEditVM can know about the PageVM - they need to exist independently. so surely my PageVM legitimately can say "I want to display this list of customers" - and give the list to the CustomerListVM?

    MVVM# - See how I did MVVM my way ___________________________________________ Man, you're a god. - walterhevedeich 26/05/2011 .\\axxx (That's an 'M')

    P M 2 Replies Last reply
    0
    • L Lost User

      Pete O'Hanlon wrote:

      the parent ViewModel has to know what views are associated with it, and hence the ViewModels that are associated with those views. This is a real no-no.

      I don't understand why you say this? Lets say I will have a page showing a list of customers, and also the individual fields from the currently selected customer. In MVVM I would create a VM for the page, and also (because the functionality is self-contained) a VM for the list of customers and a VM for the individual Customer fields (that is, ONE VM with properties for each Customer field) Now, my Page VM is nonsense without having a CustomerListVM and a CustomerEditVM somehow contained within it. It certainly doesn't know about the VIEWs but it MUST know about the ViewModels Similarly neither the customerListVM nor the CustomerEditVM can know about the PageVM - they need to exist independently. so surely my PageVM legitimately can say "I want to display this list of customers" - and give the list to the CustomerListVM?

      MVVM# - See how I did MVVM my way ___________________________________________ Man, you're a god. - walterhevedeich 26/05/2011 .\\axxx (That's an 'M')

      P Offline
      P Offline
      Pete OHanlon
      wrote on last edited by
      #7

      _Maxxx_ wrote:

      I don't understand why you say this?
       
      Lets say I will have a page showing a list of customers, and also the individual fields from the currently selected customer.
       
      In MVVM I would create a VM for the page, and also (because the functionality is self-contained) a VM for the list of customers and a VM for the individual Customer fields (that is, ONE VM with properties for each Customer field)
       
      Now, my Page VM is nonsense without having a CustomerListVM and a CustomerEditVM somehow contained within it.
       
      It certainly doesn't know about the VIEWs but it MUST know about the ViewModels
       
      Similarly neither the customerListVM nor the CustomerEditVM can know about the PageVM - they need to exist independently.
       
      so surely my PageVM legitimately can say "I want to display this list of customers" - and give the list to the CustomerListVM?

      If you check out the problem that the user describes, it's not the same issue that you are describing here. What you describe is a perfectly acceptable solution where you have one view containing data derived from several VMs, where the containing VM is still being displayed. What the OP described however was a different scenario. He has moved the implementation out of a single view into multiple views, and there is no real physical interaction between these views other than the fact that they were all originally part of one larger VM. The key point here is that the view/viewmodel interaction here is no longer with the "parent" VM, it's with the child VM. This means that, conceptually, the new VM can exist without knowledge of the old VM. The Model part, which has been entirely forgotten about in this situation, can be the same model (and is the one I would choose). So, rather than having to contort the code to worry about maintaining this disconnected list of VMs, it makes more sense to just have the child VM use the same model. Remember that a lot of people mistake the model for always being the data layer; it doesn't have to be, so a simple containing model makes this scenario a whole lot easier.

      Forgive your enemies - it messes with their heads

      My blog | My articles | MoXAML PowerToys

      L 1 Reply Last reply
      0
      • M Mycroft Holmes

        I use a different approach and I have the nasty feeling it may be incorrect. I have a navigate frame where the filter lives on the parent (which is itself a navigation frame) and when the user makes a selection the required control is displayed. Where I am probably most in error is that my VMs are static and the child VM gets some information from the parent VM, SelectedItem etc. I have also been known to have the VM service multiple view (view and dialog).

        Never underestimate the power of human stupidity RAH

        D Offline
        D Offline
        Duke Carey
        wrote on last edited by
        #8

        Thanks for the input Mycroft. I'm not a programmer - but I'm closer to being one than anybody else in our department so this stuff falls to me. One of the things I've found frustrating in learning MVVM is that there's plenty of info on the web about how to do this task or that task in MVVM, but not much that explains WHY, at least not in terms that a novice can get their head wrapped around. I thought about trying an approach very similar to yours but stalled on pursuing it. The downside to not doing this full time is that doing things by trial and error is REALLY time consuming because, for me, there's lots more error than there would be for somebody more fluent and accomplished. Since Pete responded, I have had only a few minutes to even think about what he suggested, so no real progress on it.

        M 1 Reply Last reply
        0
        • D Duke Carey

          Thanks for the input Mycroft. I'm not a programmer - but I'm closer to being one than anybody else in our department so this stuff falls to me. One of the things I've found frustrating in learning MVVM is that there's plenty of info on the web about how to do this task or that task in MVVM, but not much that explains WHY, at least not in terms that a novice can get their head wrapped around. I thought about trying an approach very similar to yours but stalled on pursuing it. The downside to not doing this full time is that doing things by trial and error is REALLY time consuming because, for me, there's lots more error than there would be for somebody more fluent and accomplished. Since Pete responded, I have had only a few minutes to even think about what he suggested, so no real progress on it.

          M Offline
          M Offline
          Mycroft Holmes
          wrote on last edited by
          #9

          Duke Carey wrote:

          I'm not a programmer

          Considering this I then ask myself why you decided to use MVVM, as it is strongly focused on testing which is very much a professional programmers criteria. I don't have a requirement to do a lot of testing myself but have found that MVVM has numerous other benefits and it does dictate a nicely structured solution. Getting the structure just right is the real challenge. Sometimes (often) the why will not make sense unless you have the same requirement and some people make stuff overly complex just for the sake of complexity. I'm pretty sure I have bastardised the MVVM concepts but then I just want the bloody thing to work and I do like simple, even if it means breaking a design principle (one of the reasons I am no longer writing articles).

          Never underestimate the power of human stupidity RAH

          L 1 Reply Last reply
          0
          • L Lost User

            Pete O'Hanlon wrote:

            the parent ViewModel has to know what views are associated with it, and hence the ViewModels that are associated with those views. This is a real no-no.

            I don't understand why you say this? Lets say I will have a page showing a list of customers, and also the individual fields from the currently selected customer. In MVVM I would create a VM for the page, and also (because the functionality is self-contained) a VM for the list of customers and a VM for the individual Customer fields (that is, ONE VM with properties for each Customer field) Now, my Page VM is nonsense without having a CustomerListVM and a CustomerEditVM somehow contained within it. It certainly doesn't know about the VIEWs but it MUST know about the ViewModels Similarly neither the customerListVM nor the CustomerEditVM can know about the PageVM - they need to exist independently. so surely my PageVM legitimately can say "I want to display this list of customers" - and give the list to the CustomerListVM?

            MVVM# - See how I did MVVM my way ___________________________________________ Man, you're a god. - walterhevedeich 26/05/2011 .\\axxx (That's an 'M')

            M Offline
            M Offline
            Mycroft Holmes
            wrote on last edited by
            #10

            At this point I introduce my bastardisation and have 1 CustomerVM that would service all 3 of your views.

            Never underestimate the power of human stupidity RAH

            L 1 Reply Last reply
            0
            • P Pete OHanlon

              _Maxxx_ wrote:

              I don't understand why you say this?
               
              Lets say I will have a page showing a list of customers, and also the individual fields from the currently selected customer.
               
              In MVVM I would create a VM for the page, and also (because the functionality is self-contained) a VM for the list of customers and a VM for the individual Customer fields (that is, ONE VM with properties for each Customer field)
               
              Now, my Page VM is nonsense without having a CustomerListVM and a CustomerEditVM somehow contained within it.
               
              It certainly doesn't know about the VIEWs but it MUST know about the ViewModels
               
              Similarly neither the customerListVM nor the CustomerEditVM can know about the PageVM - they need to exist independently.
               
              so surely my PageVM legitimately can say "I want to display this list of customers" - and give the list to the CustomerListVM?

              If you check out the problem that the user describes, it's not the same issue that you are describing here. What you describe is a perfectly acceptable solution where you have one view containing data derived from several VMs, where the containing VM is still being displayed. What the OP described however was a different scenario. He has moved the implementation out of a single view into multiple views, and there is no real physical interaction between these views other than the fact that they were all originally part of one larger VM. The key point here is that the view/viewmodel interaction here is no longer with the "parent" VM, it's with the child VM. This means that, conceptually, the new VM can exist without knowledge of the old VM. The Model part, which has been entirely forgotten about in this situation, can be the same model (and is the one I would choose). So, rather than having to contort the code to worry about maintaining this disconnected list of VMs, it makes more sense to just have the child VM use the same model. Remember that a lot of people mistake the model for always being the data layer; it doesn't have to be, so a simple containing model makes this scenario a whole lot easier.

              Forgive your enemies - it messes with their heads

              My blog | My articles | MoXAML PowerToys

              L Offline
              L Offline
              Lost User
              wrote on last edited by
              #11

              Thanks Pete - I was interpreting the OP differently - on re-reading after your post, I follow your logic. cheers

              MVVM# - See how I did MVVM my way ___________________________________________ Man, you're a god. - walterhevedeich 26/05/2011 .\\axxx (That's an 'M')

              P 1 Reply Last reply
              0
              • M Mycroft Holmes

                At this point I introduce my bastardisation and have 1 CustomerVM that would service all 3 of your views.

                Never underestimate the power of human stupidity RAH

                L Offline
                L Offline
                Lost User
                wrote on last edited by
                #12

                Mycroft Holmes wrote:

                1 CustomerVM that would service all 3 of your views.

                that's fine - but what if you want to use the customer lookup view elsewhere - not for editing a customer but for selecting a customer for some other function (say during order entry) You don't want to use that VM with all its overhead do you? soyou would end up with aniother ViewModel supporting the Customer lookup View... I appreciate you call it a bastardisation - but what you're really doing is treating the containing user control as a View, with a ViewModel, and the other two as user Controls (not views) so they don't have a view model any more than a text box or combo box would. And that's fine - I just find it very confusing if you call something a View that is really just a control - and if it's not just a control, i.e. if it is a View, then it should be modelled by a ViewModel -and a ViewModel's job is to model a view (otherwise they'd be called ViewsModels) :)

                MVVM# - See how I did MVVM my way ___________________________________________ Man, you're a god. - walterhevedeich 26/05/2011 .\\axxx (That's an 'M')

                M 1 Reply Last reply
                0
                • M Mycroft Holmes

                  Duke Carey wrote:

                  I'm not a programmer

                  Considering this I then ask myself why you decided to use MVVM, as it is strongly focused on testing which is very much a professional programmers criteria. I don't have a requirement to do a lot of testing myself but have found that MVVM has numerous other benefits and it does dictate a nicely structured solution. Getting the structure just right is the real challenge. Sometimes (often) the why will not make sense unless you have the same requirement and some people make stuff overly complex just for the sake of complexity. I'm pretty sure I have bastardised the MVVM concepts but then I just want the bloody thing to work and I do like simple, even if it means breaking a design principle (one of the reasons I am no longer writing articles).

                  Never underestimate the power of human stupidity RAH

                  L Offline
                  L Offline
                  Lost User
                  wrote on last edited by
                  #13

                  Mycroft Holmes wrote:

                  I do like simple, even if it means breaking a design principle (one of the reasons I am no longer writing articles).

                  I think knowingly breaking a principle for a good reason is a good thing - after all, someone decided upon a principle, it wasn't handed down on some rock tablet from a burning bush (sorry, religion not my strong point - but you see what I mean) So if you have need to break a design, with knowledge of the design and knowing you are breaking it, then I think you should not only do so, but you should also write articles specifically about it. I know I have seen people using MVVM write pages of XAML and C# code because they don't want to write any code-behind - although the code-behind is probably three lines and makes perfect sense. I say, break the principle by all means- but break it with the knowledge that you are breaking it, and why you are breaking it, and do so with head held high. (cue stirring music(

                  MVVM# - See how I did MVVM my way ___________________________________________ Man, you're a god. - walterhevedeich 26/05/2011 .\\axxx (That's an 'M')

                  P 1 Reply Last reply
                  0
                  • L Lost User

                    Mycroft Holmes wrote:

                    1 CustomerVM that would service all 3 of your views.

                    that's fine - but what if you want to use the customer lookup view elsewhere - not for editing a customer but for selecting a customer for some other function (say during order entry) You don't want to use that VM with all its overhead do you? soyou would end up with aniother ViewModel supporting the Customer lookup View... I appreciate you call it a bastardisation - but what you're really doing is treating the containing user control as a View, with a ViewModel, and the other two as user Controls (not views) so they don't have a view model any more than a text box or combo box would. And that's fine - I just find it very confusing if you call something a View that is really just a control - and if it's not just a control, i.e. if it is a View, then it should be modelled by a ViewModel -and a ViewModel's job is to model a view (otherwise they'd be called ViewsModels) :)

                    MVVM# - See how I did MVVM my way ___________________________________________ Man, you're a god. - walterhevedeich 26/05/2011 .\\axxx (That's an 'M')

                    M Offline
                    M Offline
                    Mycroft Holmes
                    wrote on last edited by
                    #14

                    Oh I'm flexible, for simple list/add dialog/detail I often have 2 views and a dialog using the same VM. If a view is particularly complex then it gets it's own VM even if that is duplicating info already in an existing VM. And no I have no intention of renaming them VsM :laugh:

                    _Maxxx_ wrote:

                    I just find it very confusing if you call something a View that is really just a control

                    The list view is the entry point into the structure, the detail view is distinct, navigated to via a double click from the datagrid on the list view, the add dialog is obviously a childwindow from the list view. All 3 use the same VM, calling the detail view a control is not correct, the dialog maybe.

                    Never underestimate the power of human stupidity RAH

                    L 1 Reply Last reply
                    0
                    • M Mycroft Holmes

                      Oh I'm flexible, for simple list/add dialog/detail I often have 2 views and a dialog using the same VM. If a view is particularly complex then it gets it's own VM even if that is duplicating info already in an existing VM. And no I have no intention of renaming them VsM :laugh:

                      _Maxxx_ wrote:

                      I just find it very confusing if you call something a View that is really just a control

                      The list view is the entry point into the structure, the detail view is distinct, navigated to via a double click from the datagrid on the list view, the add dialog is obviously a childwindow from the list view. All 3 use the same VM, calling the detail view a control is not correct, the dialog maybe.

                      Never underestimate the power of human stupidity RAH

                      L Offline
                      L Offline
                      Lost User
                      wrote on last edited by
                      #15

                      Mycroft Holmes wrote:

                      All 3 use the same VM, calling the detail view a control is not correct, the dialog maybe.

                      I see exactly what you're talking about - and it's really down to terminology - but in my view (pub intended) the VM models a V, and if there isn't a specific Vm then it's not a V, it's just a control - as it cannot be used (or tested) stand-alone. It was partly because of this that I introduced the concept of ViewData separate from (but used by) the ViewModel

                      MVVM# - See how I did MVVM my way ___________________________________________ Man, you're a god. - walterhevedeich 26/05/2011 .\\axxx (That's an 'M')

                      1 Reply Last reply
                      0
                      • L Lost User

                        Thanks Pete - I was interpreting the OP differently - on re-reading after your post, I follow your logic. cheers

                        MVVM# - See how I did MVVM my way ___________________________________________ Man, you're a god. - walterhevedeich 26/05/2011 .\\axxx (That's an 'M')

                        P Offline
                        P Offline
                        Pete OHanlon
                        wrote on last edited by
                        #16

                        No problems mate. It took me two readings to get what he wanted right in my head.

                        Forgive your enemies - it messes with their heads

                        My blog | My articles | MoXAML PowerToys | Mole 2010 - debugging made easier - my favourite utility

                        1 Reply Last reply
                        0
                        • L Lost User

                          Mycroft Holmes wrote:

                          I do like simple, even if it means breaking a design principle (one of the reasons I am no longer writing articles).

                          I think knowingly breaking a principle for a good reason is a good thing - after all, someone decided upon a principle, it wasn't handed down on some rock tablet from a burning bush (sorry, religion not my strong point - but you see what I mean) So if you have need to break a design, with knowledge of the design and knowing you are breaking it, then I think you should not only do so, but you should also write articles specifically about it. I know I have seen people using MVVM write pages of XAML and C# code because they don't want to write any code-behind - although the code-behind is probably three lines and makes perfect sense. I say, break the principle by all means- but break it with the knowledge that you are breaking it, and why you are breaking it, and do so with head held high. (cue stirring music(

                          MVVM# - See how I did MVVM my way ___________________________________________ Man, you're a god. - walterhevedeich 26/05/2011 .\\axxx (That's an 'M')

                          P Offline
                          P Offline
                          Pete OHanlon
                          wrote on last edited by
                          #17

                          _Maxxx_ wrote:

                          I say, break the principle by all means- but break it with the knowledge that you are breaking it, and why you are breaking it

                          Exactly so. As I've often told people, MVVM is just a tool to use. It should never become dogma - if it does that, then it's failed in it's intended purpose of making WPF/SL development easier to accomplish.

                          Forgive your enemies - it messes with their heads

                          My blog | My articles | MoXAML PowerToys | Mole 2010 - debugging made easier - my favourite utility

                          1 Reply Last reply
                          0
                          Reply
                          • Reply as topic
                          Log in to reply
                          • Oldest to Newest
                          • Newest to Oldest
                          • Most Votes


                          • Login

                          • Don't have an account? Register

                          • Login or register to search.
                          • First post
                            Last post
                          0
                          • Categories
                          • Recent
                          • Tags
                          • Popular
                          • World
                          • Users
                          • Groups