Hi friends out there.
I want to know how i can add control or usercontrol in layout control like canvas at runtime in MVVM. As i don't want to add any code in code behind file of my view and i am unable to figure out how i can do in MVVM.
please tell me how i achieve that.
Thanks in advance.
Aug 6, 2012 at 7:22 PM
As far as I know, it's not possible to set the elements of a Canvas
control through a data binding. Therefore, you will need to add the corresponding controls to the
Canvas manually (this also includes setting the Canvas.Left and
Canvas.Top attached properties.)
Based on my understanding, when implementing the MVVM pattern, the
view is responsible for defining any UI specific logic in its code-behind. Also, the
view model should not know how to modify the UI components of the
view directly. Therefore, while the view model could expose a list of controls to add to the
view, the logic to display those controls in the Canvas
should be placed in the view's code-behind.
I believe you can find the following thread interesting, where a similar scenario was discussed:
On the other hand, if you wish to handle this scenario in a more decoupled fashion and without adding code in the view's code-behind, I believe you can take advantage of the
UI Composition capabilities provided by Prism. Although
Prism as out of the box does not provide support for using
Canvas or any other "layout pane" controls as a Region, you could define your own custom
RegionAdapters for controls such as Canvas. Then, you could define the aforementioned
Canvas in the view as a Region, and in the
view model inject the corresponding controls as you would do with views in a
You can find more information about creating your RegionAdapters, in the following chapter of the
I hope you find this useful,