3
votes

I am totally new to WPF. I'm using DevExpress mvvm framework. I want to show a window from a viewmodel.

The code I am using is

    public void NewEntity()
    {           
        var factory = ViewModelSource.Factory((RemoteTable<AddressLocatorView> aRemoteTable) => new CreateEntityWizardViewModel(aRemoteTable));
        CreateEntityWizardViewModel aVM = factory(fDataModule.DataAdapter.GetTable<AddressLocatorView>());
        DialogService.ShowDialog(dialogCommands: null, title: "New Entity Wizard", viewModel: aVM);
    }

This will open a form and set the viewmodel.

Though, in the form's constructor, I have

    public CreateEntityWizard()
    {
        InitializeComponent();
    }

Which, in turn, calls the public parameterless constructo of the EntityWizardViewModel. The EntityWizardViewModel is created twice, once by the factory method, and second by the InitializeComponent() which, I believe, does it by the means of the XAML :

         DataContext="{dxmvvm:ViewModelSource Type={x:Type ViewModels:CreateEntityWizardViewModel}}"

What is the approach to pass a ViewModel to a form using the DialogService ?

Thank you

1

1 Answers

1
votes

When you pass your view model to the DialogService.ShowDialog method, this view model is automatically used as data context for the associated view (your dialog content). Therefore, the best way to avoid duplicate view model creation is to remove the DataContext setter in xaml. To let the designer know your data context type, use the d:DataContext property:

xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
d:DataContext="{dxmvvm:ViewModelSource ViewModel:RegistrationViewModel}"

This approach is used for RegistrationViewModel in the following example on the DevExpress website: https://www.devexpress.com/Support/Center/e/T145641.aspx