简体   繁体   中英

How do I set DataContext of a View to ViewModel when using DialogService

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.
}

In your XAML, there will be a Loaded event on the dialog itself eg

<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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM