简体   繁体   English

不同视图的ViewModel初始化方法

[英]ViewModel Initialize method for different Views

I have a TabbedPage which shows deliveries in progress and finished deliveries. 我有一个TabbedPage,它显示进行中的交货和已完成的交货。 The model for both views is the same, only the service method from where we get the data is different, so I would like to reuse the ViewModel. 两种视图的模型相同,只是从中获取数据的服务方法不同,因此我想重用ViewModel。

Would it be a good solution to reuse the ViewModel by passing some navigation data into my InitializeAsync method that would allow me to decide which service method to use to get the data for the view? 通过将一些导航数据传递到InitializeAsync方法中来重用ViewModel,这将是一个很好的解决方案,该方法可以让我决定使用哪种服务方法来获取视图数据?

I would override OnCurrentPageChanged in TabbedPage View's code-behind and Initialize the ViewModel from there 我将在TabbedPage View的代码中覆盖OnCurrentPageChanged并从那里初始化ViewModel

TabbedPageView.xaml.cs TabbedPageView.xaml.cs

    protected override async void OnCurrentPageChanged()
    {
        base.OnCurrentPageChanged();
        if (!(CurrentPage.BindingContext is TabbedPageViewModel tabbedPageViewModel)) return;
        if (CurrentPage == DeliveriesInProgress)
        {
            await tabbedPageViewModel.InitializeAsync("DeliveriesInProgress");
        }
        else if (CurrentPage == FinishedDeliveries)
        {
            await tabbedPageViewModel.InitializeAsync("FinishedDeliveries");
        }
    }

TabbedPageViewModel.cs TabbedPageViewModel.cs

    public async Task InitializeAsync(object navigationData)
    {
        if (navigationData is string deliveryType)
        {
            if (deliveryType == "InProgress")
            {
                Deliveries = await _deliveryService.GetDeliveriesInProgress();
            }
            else if (deliveryType == "Finished")
            {
                Deliveries = await _deliveryService.GetFinishedDeliveries();
            }
        }
    }

What could be alternative solutions? 什么是替代解决方案?

The best way is to use two different properties in your viewmodel. 最好的方法是在视图模型中使用两个不同的属性。 Then you can bind the two different views in the tabs to the associated property. 然后,您可以将选项卡中的两个不同视图绑定到关联的属性。

In your viewmodel: 在您的视图模型中:

public ObservableCollection<MyDeliveryModel> FinishedDeliveries;
public ObservableCollection<MyDeliveryModel> DeliveriesInProgress;

Know you can add two methods to load the data for those properties: 知道您可以添加两种方法来加载这些属性的数据:

public async Task RefreshFinishedAsync() 
{ 
    // Your logic to load the data from the service
}
public async Task RefreshInProgressAsync()
{ 
    // Your logic to load the data from the service
}

And then in your TabbedPage-Event: 然后在您的TabbedPage-Event中:

if (CurrentPage == DeliveriesInProgress)
{
    await tabbedPageViewModel.RefreshInProgressAsync();
}
else if (CurrentPage == FinishedDeliveries)
{
    await tabbedPageViewModel.RefreshFinishedAsync();
}

With this solution you can separate the data and you don't need to reload the whole data everytime you change the tabs. 使用此解决方案,您可以分离数据,并且每次更改选项卡时都不需要重新加载整个数据。 You can check if there is already some data in the collection, and if so... just don't reload the data. 您可以检查集合中是否已经有数据,如果有的话...只是不重新加载数据。 Just do it if the user wants it. 如果用户需要,请执行此操作。

This improves the performance and the "wait-time" for the user. 这改善了性能和用户的“等待时间”。

Or as an alternative: Load all data at once and just filter the data for the two collection-properties. 或者作为替代方案:一次加载所有数据,然后仅过滤两个collection-properties的数据。 This reduces the service-calls. 这减少了服务呼叫。

You can accomplish this by using a base viewmodel and a view model for each tab that uses the base. 您可以通过使用基础视图模型和使用基础视图的每个选项卡的视图模型来完成此操作。 The base then holds your commands and deliveries. 基地然后保存您的命令和交付。 you bind each tabbed page to the viewmodel for that page so you won't need to check on tab changed. 您将每个选项卡式页面绑定到该页面的视图模型,因此您无需检查更改的选项卡。 When you construct each viewmodel, pass in the information needed to base to know how to query the data. 构造每个视图模型时,请传递基础知识所需的信息以了解如何查询数据。 For each tabbed view, if the views are the same for in progress and finished, use a partial view and put it in both tabbed pages. 对于每个选项卡式视图,如果进行中和完成的视图相同,请使用部分视图并将其放在两个选项卡式页面中。 This gives flexibility in the long run. 从长远来看,这提供了灵活性。

public class InProgressDeliveriesViewModel: BaseDeliveryViewModel{

     public InProgressDeliveriesViewModel():base(filterParams){}
}

public class FinishedDeliveriesViewModel: BaseDeliveryViewModel{

     public FinishedDeliveriesViewModel():base(filterParams){}
}

public class BaseDeliveryViewModel{

   private FilterObjectOfSomeSort _filterParams;

   public BaseDeliveryViewModel(filterParams whatever){
      //use these params to filter for api calls, data.  If you are calling the same 
      //endpoint pass up the filter
      _filterParams = whatever;
    }

   public ObservableCollection<MyDeliveryModel> Deliveries {get;set;}

   public async Task LoadDeliveries(){
       //use the filter params to load correct data
       var deliveries = await apiClient.GetDeliveries(filterParams); //however you 
       //are gathering data
   }

.... All of your other commands

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从不同的视图模型中调用一个视图模型中的方法 - Calling a method in one viewmodel from a different viewmodel 在不同视图中共享ViewModel时,ModelState失败 - ModelState fails when sharing a ViewModel in different Views 如果不同的视图共享同一视图模型,如何从视图模型中选择视图 - How to select a view from a viewmodel if different views share the same viewmodel 从其他ViewModel调用方法 - Calling a method from a different ViewModel 使方法对不同的视图模型通用 - make method generic for different viewmodel Xamarin.Forms ViewModel 中的异步方法不等待 AzureServiceTokenProvider 和 SqlConnection 初始化 - Async method in Xamarin.Forms ViewModel not waiting for AzureServiceTokenProvider and SqlConnection to initialize 在WPF中,是否可以根据某些条件用不同的视图表示同一ViewModel? - In WPF, is it possible to represent the same ViewModel with different Views, based on some condition? 一个ViewModel包含ViewModel的集合,不同的View取决于ViewModel属性的值 - One ViewModel containing a collection of ViewModels, different Views depending on value of ViewModel property 为每个页面共享 ViewModel 数据,同时为不同的视图重用单个 ViewModel - ViewModel data is being shared for each Page while Reusing single ViewModel for different Views 无法构造和初始化viewModel - Unable to construct and initialize viewModel
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM