WPF sets up DataContext via constructor

As I understand it, when I bind my ViewModel to my View, this is done via the DataContext. Something like

   <Grid.Resources>
        <myData:MyVM x:Key="Vm" />
    </Grid.Resources>
    <Grid.DataContext>
        <Binding Source="{StaticResource Vm}"></Binding>
    </Grid.DataContext>

      

My understanding of how the ViewModel is populated is the view calling the ViewModel (via binding) and the ViewModel interacts with the model and does what ever needs to be done to force itself (the ViewModel) into the desired state.

So what happens if your "Model" is created by the user interface? My Model is a parameter of my MainWindow Constructor.

So my View (MainWindow) -

public MainWindow(MyObject myObject)
    {
          InitializeComponent();
    }

      

My ViewModel

 public class ViewModel 
{
    #region properties

    private MyObject myList;
    public MyObject MyList
    {
        get; set ;
    }

    #region Constructors

    public ViewModel ()
    {

    }

    public ViewModel (MyObject myObject)
    {
        this.myObject= myObject;
    }        
}

      

Now that my application is running (and I'm sure I'm using the wrong words here), how do I "enter" my parameter into the ViewModel? Or do we feel there is a better approach?

EDIT

Explaining what I am trying to achieve might help. My program does some tasks and creates a log. The log is kept in memory. At the end of my programming processes, the log is displayed on the screen. This is why I am passing the object to the constructor.

+3


source to share


2 answers


Or do we feel there is a better approach?

I would prefer that you bind your view to your view model. If you are going to follow the MVVM pattern, then this is one way to do it. Now, I can't be sure if you are using dependency injection, but you are specifying "inject" in your question, so I assume you are. Here's some sample code:

INSTALL THE DATACONTEXT OF YOUR VIEWER TO YOUR VIEWER:

 public YourView(IUnityContainer container)
        {
            InitializeComponent();
            this.DataContext = container.Resolve<IYourViewModel>();
        }

      



YOUR MODEL AGAIN IN YOUR VIEW MODEL:

 private YourModel _yourModel;

 public YourViewModel(YourModel yourModel)        
        {
            _yourModel = yourModel;
            InitializeDelegateCommands();
        }

      

So now your viewmodel is attached to your view. All model interactions must be coordinated across the view model.

+2


source


Don't forget to add InitializeComponent()

to your constructor MainWindow

.



public MainWindow(MyObject myObject)
{
    InitializeComponent();
}

      

+1


source







All Articles