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?
As you can see, if we want to display more than one Model into a single View, we have to pass a ViewModel to that View, so that we can take benefits of both the models into a single object. So, we have to use ViewModel for better performance of sources.
The purpose of ViewModel is to encapsulate the data for a UI controller to let the data survive configuration changes. For information about how to load, persist, and manage data across configuration changes, see Saving UI States.
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 which ViewModel
(VM
) will talk to View
with the required method(s)
public interface IView { void AddTextBoxToGrid(); }
2) Inherit code behind View
from your IView
and implement IView.AddTextboxToGrid()
method
public partial class View: IView { public void AddTextBoxToGrid() { // implement here your custom view logic using standard code behind; } }
3) Add a property of type IView
to your VM
public class ViewModel { public IView View { get; set; } }
4) Set View
property on VM
to an instance of View
as IView
e.g. in code behind:
DataContext.View = this as IView;
or in Caliburn you can use IScreen.OnViewAttached override method)
public partial class View: IView { public View() { // access you VM by the strategy of your framework or choice - this example is when you store your VM in View's DataContext (DataContext as ViewModel).View = this as IView; } public void AddTextBoxToGrid() { // implement here your custom view logic using standard code behind; } }
5) In your VM
call IView.AddTextboxToGrid()
public class ViewModel { public IView View { get; set; } public void AddTextBoxToGrid() { if (View == null) return; View.AddTextBoxToGrid() } }
You should move your creation code to View, and ViewModel should just notify view when it should be called.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With