sahithi
sahithi

Reputation: 1089

Binding control details from ViewModel is taking long time for ListView in xamarin.forms

I am working on xamarin.forms application, there I have a list view with 11 Stack layouts and different designs for each stackLayout.

Here, all the colors and visibilities for all controls in the stack layout are binded from the viewModel.

The problem is while loading the application the listview is loading for view but there it is taking about to 10-30 sec of time to bind the design for the listview from the ViewModel.

<ListView x:Name="itemslist" ItemsSource="{Binding listViewItems}" CachingStrategy="RecycleElement" HasUnevenRows="true" SeparatorVisibility="None" HorizontalOptions="FillAndExpand" BackgroundColor="#e7ebee" ItemSelected="OnItemSelected">
                <ListView.ItemTemplate>
                    <DataTemplate>
                    <controls:CustomViewCell/>

                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>

My custom viewCell is as following structure:

<StackLayout>
   <StackLayout x:Name="Type1">
        <Frame>
              Combination of Buttons, pickers and editor
        </Frame>
     </StackLayout>
.........................................................
 <StackLayout x:Name="Type11">
        <Frame>
              Combination of Buttons, pickers and editor
        </Frame>
     </StackLayout>
</StackLayout>

This custom viewcell consists of 11 stacklayouts with different designs each.

Is there any way to make the design to load quickly to view. ]

Upvotes: 0

Views: 176

Answers (1)

Daniel
Daniel

Reputation: 9521

You are right. This is not the best way to do it because you instantiate a lot of visual elements that are not useful to the end user when loading your list.

This is how I would do it:

  1. Separate each view in a ContentView
  2. Create a view that gather them all but only intatiates the view when necessary That would be something like (you don't need xaml here):

public class ContentView1 : ContentView { public ContentView1 () { ... }

protected override void OnBindingContextChanged()
{
    base.OnBindingContextChanged();
    if (BindingContext is MyViewModel vm)
    {
        _vm = vm;
        vm.PropertyChanged += VmOnPropertyChanged;
    }

//don't forget to detach the event handler if _vm is not null }

private void VmOnPropertyChanged(object sender, PropertyChangedEventArgs e)
{
    if (e.PropertyName == nameof(MyViewModel.MyProperty))
    {
        switch (_vm.MyProperty)
        {
            case 1:
                Content = new View1();
                break;
            case 2:
                Content = new View2();
                break;
            [...]
        }
    }
}

}

That way, you intantiate the view number "n" only when you need it.

Upvotes: 0

Related Questions