You tagged with this MVVM, so this answer is going to be based on using MVVM.
The View should not ever create objects or try to assign values... it is only meant to be a user-friendly reflection of the ViewModel/Models that users can use to interact with.
What you have now appears to be :
- AppStartup creates EF dbContext, and assign it to View.DataContext
- View creates ViewModel, and tries to pass it the EF dbContext
This is incorrect, because the View should not be responsible for creating objects or assigning values like this.
What you want for MVVM is
- AppStartup
- Creates ViewModel and EF dbContext
- Sets dbContext to ViewModel
- Creates View, and assigns ViewModel to View.DataContext
- View displays ViewModel to user and allows them to interact with it
So what you should have is something like this :
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
var app = new MainWindow();
var dbContext = new MyEntities();
var context = new MyViewModel(dbContext);
app.DataContext = context;
app.Show();
}
AppStartup is responsible for any kind of application initialization, such as creating the EF DataContext or ViewModels.
From the View, you could write something like
<DataTemplate DataType="{x:Type local:SearchEmployeeViewModel}">
<userControl:SearchEmployeeControl />
</DataTemplate>
and this will tell WPF
Anytime you encounter an object of type SearchEmployeeViewModel
in the VisualTree, draw it using SearchEmployeeControl
, and set the DataContext
of that control to SearchEmployeeViewModel
.
Typically ViewModels are inserted into the UI via the Content
or ItemsSource
property, like this :
<ContentControl Content="{Binding SearchEmployeeViewModel}" />
<TabControl Content="{Binding TabViewModels}" />
I also have a Simple MVVM Example on my blog if you're interested in learning more, or I'd highly recommend reading What is this "DataContext" you speak of? if you are very new to WPF and still don't have a firm understanding of what the DataContext is or how it works.
That said, if you wanted to have your View assign the value of the ViewModel as you have in your question, your options are either
- Assign the property via Code Behind the View
- Change
ViewModel.Context
to a DependencyProperty, and bind it using OneWayToSource
binding mode, meaning the binding will only work by transferring values from the View to the ViewModel.
I do not recommend either of these and would rather redesign to do this properly in MVVM, however if I were forced to pick one I would choose to use code behind. You're already breaking a bunch of rules at this point, so why not one more :)