Search code examples
wpfmvvmdatacontext

How to properly pass parameters between modelView and View for the datacontext


I have the following: - class AccountViewModel : BaseViewModel - AccountView.xaml

I'm struggling to pass parameters to the ModelView.

in the main window, I bind them together:

<DataTemplate DataType="{x:Type local:AccountViewModel}">
     <local:AccountView />
</DataTemplate>

In the mainWindowViewModel, I have an action to display the Account view by doing:

ChangeViewModel(new AccountViewModel(new DateTime(2016, 2, 06), new DateTime(2016, 2, 15)))

As you can see, the AccountViewModel takes 2 arguments for its constructor, 2 Datetime.

Then in the AccountView, I try to create a DataContext by doing:

<UserControl.DataContext>
    <ObjectDataProvider ObjectType="local:AccountViewModel"
    xmlns:sys="clr-namespace:System;assembly=mscorlib">
        <ObjectDataProvider.ConstructorParameters>
            <sys:DateTime></sys:DateTime>
            <sys:DateTime></sys:DateTime>
        </ObjectDataProvider.ConstructorParameters>
    </ObjectDataProvider>
</UserControl.DataContext>

Whatever I do, it will create another instance of AccountViewModel. I don't want that, I want this AccountView to keep using the AccountViewModel I created in the command shown above but I also want to use the binding functionality. I would rather try to avoid using the code behind if possible.

How can I achieve this?


Solution

  • You don't need to create an extra object on your ViewModel. When your View is Defined by your DataTemplate DataType. It will automatically passed to your View.

    See this answer to understand DataContext here

    Remove your below code from your View and check the DataContext, it will be local:AccountViewModel:

    <UserControl.DataContext>
    <ObjectDataProvider ObjectType="local:AccountViewModel"
    xmlns:sys="clr-namespace:System;assembly=mscorlib">
        <ObjectDataProvider.ConstructorParameters>
            <sys:DateTime></sys:DateTime>
            <sys:DateTime></sys:DateTime>
        </ObjectDataProvider.ConstructorParameters>
    </ObjectDataProvider>