Reputation: 303
I have been following this pattern. http://www.codeproject.com/Articles/36745/Showing-Dialogs-When-Using-the-MVVM-Pattern
However, in this example, in the PersonDialog.xaml.cs class, I'm not able to access this.DataContext. It's always null. Since I'm using DialogService to open a window(where I'm setting the DataContext there to ViewModel and also passing on the data to PersonDialogViewModel from MainWindowViewModel) I need that instance of ViewModel. I'll not be able to create another PersonDialogViewModel from View.
Please suggest as I need to access Data from the ViewModel in the code behind.
Here is the code.
//MainWindowViewModel.cs
PersonViewModel selectedPerson = persons.Single(p => p.IsSelected);
PersonDialogViewModel personDialogViewModel = new PersonDialogViewModel(selectedPerson.Person);
dialogService.ShowDialog<PersonDialog>(this, personDialogViewModel);
//In PersonDialogViewModel.cs
public PersonDialog()
{
InitializeComponent();
var obj = this.DataContext;//DataContext is always null.
}
Upvotes: 0
Views: 543
Reputation: 336
In your XAML, there will be a Loaded event on the dialog itself e.g.
<UserControl
x:Class="ClassName"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:D="http://schemas.microsoft.com/expression/blend/2008"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Loaded="UserControl_OnLoaded"
Mc:Ignorable="D">
This "UserControl_OnLoaded" event handler will be a method in your code behind. If you perform
var obj = this.DataContext;
At that point, then the data context will be set. The contructor is the point where the PersonDialog is constructed, not when the DataContext has been bound to it by your dialog service.
Upvotes: 1