How to pass an object to a ViewModel using dependency injection?

I need to pass an object from one view model to another. In my current implementation, I created a static instance of ProductVM, following this example , and then accessed this property from the instance. But the transfer of a static instance in the long run does not seem continuous.

private static ProductVM _instance = new ProductVM();
public static ProductVMInstance { get { return _instance; } }

When exploring alternatives to providing an instance of a static view model, I came across constructor injection as an option.

Question:

Does anyone have an example how to implement ctor injection to pass objects? (It is preferable not to use a third-party structure)

VM Products: (view the model containing the property to be sent)

    public ProductModel SelectedProduct { get; set; }

CustomerOrdersVM: ( , )

public class CustomerOrdersViewModel : IPageViewModel
{

    public CustomerOrdersViewModel()
    {                  

    }
}
+4
2

. 1 2 " ". , SelectedProduct, ProductVM CustomerOrdersVM. , - viewmodel, "", CustomerOrdersVM ProductVM (, , , CustomerOrdersVM ctor):

public class MainViewModel : ViewModelBase
{
    public MainViewModel()
    {
        ProductsViewModel = new ProductsVM();
        OrdersViewModel = new CustomerOrdersVM(ProductsViewModel);
    }
    public CustomerOrdersVM OrdersViewModel { get; private set; }

    public ProductsVM ProductsViewModel { get; private set; }
}

MVVM ( ), . , ( , ), viewmodels. , , , , . , / , , , .

... CustomerOrderVM? , SelectedProduct ProductsVM, CustomerOrdersVM ? , EventAggregator? - , . eventaggregator . , , ProductVM , CustomerOrdersVM .

+1

Rowbear EventAggregators. .

EventAggregator , ViewModel ( ) , ViewModel , .

, ViewModel/View , . , - .

, (productId, orderId ..) , navigationService.Navigate("OrderDetails", orderId);, ViewModels - INavigationAware , , ViewModel .

public class OrderDetailsViewModel : ViewModelBase, INavigationAware
{
    public async void OnNavigatedFrom(object parameter) 
    {
        var orderId = (int)parameter;
        var order = await orderRepository.GetOrderByIdAsync(orderId);

        // display your order in the ViewModel here
    }
}

, , , Prism MVVM ( Microsoft).

+1

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


All Articles