I have a WPF Window, and in that window I have a grid.
I use M-V-VM model and I want to add a TextBox to the grid dynamically in code(in viewmodel)
How can I get access to the grid?
I have a WPF Window, and in that window I have a grid.
I use M-V-VM model and I want to add a TextBox to the grid dynamically in code(in viewmodel)
How can I get access to the grid?
You should move your creation code to View, and ViewModel should just notify view when it should be called.
If you are using Caliburn Micro, implement following step:
Make the ViewModel inherited from interface
IViewAware
; you are going to implement two methods AttachView and GetView of this interface.Define a variable with type of View to get the reference to the View
See detail below:
Later on you can access a single element on the View through v such as v.txtName="John"; etc...
Use Supervising Controller pattern.
Reading:
Example implementation for CaliburnMicro MVVM framework is shown here (will work same for all other frameworks - or you can do it by hand if you are doing MVVM by yourself):
http://drc.ideablade.com/devforce-2012/bin/view/Documentation/cocktail-tutorial-talk-to-view
Example:
1) Define interface
IView
in whichViewModel
(VM
) will talk toView
with required method(s)2) Inherit code behind
View
from yourIView
and implementIView.AddTextboxToGrid()
method3) Add property of type
IView
to yourVM
4) Set
View
property onVM
to instance ofView
asIView
e.g. in code behind DataContext.View = this as IView; or in Caliburn you can use IScreen.OnViewAttached override method)5) In your
VM
callIView.AddTextboxToGrid()
You can also use the DataContext (which is the ViewModel) of the View in the code behind of the view, and add the textbox to the grid there. That would make more sense.
If you give the grid a name in your XAML file, you will be able to access the grid in the code behind immediately.