Any way to get a control from the view in the viewmodel without using Commands?

Topics: Prism v2 - Silverlight 3
Dec 9, 2009 at 2:13 AM

Hi all,

I have a control in a view and I need to do something about it in its associated viewmodel's constructor.
I know I can use a ClickCommand and then pass the control as a parameter but really I want this to happen when the view/viewmodel is loaded...

Something like this:

public MyViewModel()
            // here needs to assign the control to a method
            someMethod.ControlToUse = controlNameInTheView;

Is this possible??

Any help would be much appreciated!


Dec 9, 2009 at 1:23 PM

Hi Xin,

While you could expose the control  as a property of the view to have access to it in the ViewModel this is not the recommended approach. The ViewModel should not know about the controls you are using, as that is mostly UI related. Without fully knowing the scenario I can think of two options:

  • If possible use bindings to achieve the desire functionality in your control.
  • If the above is not viable, you can always perform your required actions in the View’s constructor. As the view is in charge of handling UI related concerns, this would be the place to do it if necessary.

In my personal opinion if you require a particular control instance to run a method, which is something UI related, you might consider adding this kind of code to the View’s code-behind as well.

You can read more about using MVVM with Prism in this blog post.

Please let me know if this helps.

Damian Schenkelman