Post MVVM View and ViewModel using declarative DataContext for Design-Time and Data Template for Runtime?

Is it possible to connect View and ViewModel using both declarative DataContext and data template?

Purpose . I want to connect Views using one ViewModel for development time and another at runtime. Currently, using declarative DataContext for VM development time and the virtual machine specified in the data template for the runtime does not behave as expected.

Background . There are many ways to connect View and ViewModel, including the following:

A.) Declaratively specify the DataMonel ViewModel in XAML views . This method is useful in Design-Time, using a parameterless constructor for passing in dummy data.

<UserControl.DataContext> <my: BrowseAssetsViewModel /> </UserControl.DataContext> 

B.) Programmatically specify ViewModel, View, and DataContext .

 // …Setup code BrowseAssetsViewModel viewModel = new BrowseAssetsViewModel(assetRegistry, domains); BrowseAssetsView view = new BrowseAssetsView(); view.DataContext = viewModel; 

When approach B is used in combination with approach A, at run time, WPF overrides the standard DataContext specified in approach A using the ViewModel version with the parameterized constructor specified in approach B.

C.) Define a data template for the View-ViewModel association . By linking View and ViewModel in App.XAML Application.Resources, WPF can connect the correct view based on the ViewModels type.

 <DataTemplate DataType="{x:Type vm: BrowseAssetsViewModel }"> <vw: BrowseAssetsView /> </DataTemplate> 

If the ViewModel property was bound to a ContentPresenter control, WPF hooked up the appropriate view (based on the ViewModels type) and placed it inside the ContentPresenter. This is useful in the "ViewModel-first" scenario where the ViewModel is presented, and WPF enables and parses the correct View by checking the presented ViewModels type.

Problem . When using this approach, C combined with approach A, WPF allows the correct view, but it seems to re-request the view by invoking the declaratively specified ViewModel using a parameterless constructor (Approach A), thus overriding the existing ViewModel!

Question: Is there a way to use these methods (C and A) together without A by inadvertently rewriting the C property of the ViewModel?

+6
source share
1 answer

You can specify that a DataContext in case A is set only during development, for example:

 <UserControl ... d:DataContext="{d:DesignInstance my:BrowseAssetsViewModel}" > 

See Using DesignInstance ... on MSDN for more information.

+8
source

Source: https://habr.com/ru/post/901465/


All Articles