Home > database >  Any alternatives to the switching different groups of Page elements visibility in .net Maui?
Any alternatives to the switching different groups of Page elements visibility in .net Maui?

Time:08-28

I need to build a page which has some static "always there" elements, and some alternate groups of elements that show up and hide depending on user actions.

One approach could be combine each group of elements into some container like StackLayout and control their visibility, like this:

<StackLayout IsVisible="{Binding IsLoaded}">...</StackLayout>

<StackLayout IsVisible="{Binding IsLoaded}, Converter={helpers:InverseBoolConverter}">...</StackLayout>

However if there are more than 2 such groups of such elements, more overhead is added, and I feel like a better way of implementing that must exist.

What I've found is DataTemplateSelector, however: it seems to work for "list of items" type of controls. I wonder if something similar exists for a ContentPage or non-list controls, so I can define 2 or more alternative templates (or controls) with bindings to the same ViewModel inside, and based on the page ViewModel data switch their visibility: ViewModel.IsLoaded=true display one template/control, otherwise display the other.

Note: different control styling won't be enough for my scenario, it's different set of controls.

CodePudding user response:

StackLayout can specify a DataTemplateSelector in its BindableLayout.ItemTemplateSelector:

<StackLayout BindableLayout.ItemsSource="{Binding Source}" 
             BindableLayout.ItemTemplateSelector="{StaticResource TemplateSelector}"/>

BindableLayout.ItemsSource might be a collection containing one item:

Source = new ObservableCollection<Model>
{ 
  model
};

The DataTemplateSelector might be triggered as follows:

Source.Clear();
Source.Add(model);

Sample DataTemplateSelector:

public class TemplateSelector : DataTemplateSelector
{
  public DataTemplate DataTemplate1 { get; set; }

  public DataTemplate DataTemplate2 { get; set; }

  protected override DataTemplate OnSelectTemplate(object item, BindableObject container)
  {
    Model model = item as Model;

    // Determine template; DataTemplate1 or DataTemplate2

    return template;
  }
}

Sample usage in XAML:

<DataTemplate x:Key="DataTemplate1">
...
<DataTemplate x:Key="DataTemplate2">
...
<namespace:TemplateSelector x:Key="TemplateSelector" 
  DataTemplate1="{StaticResource DataTemplate1}" 
  DataTemplate2="{StaticResource DataTemplate2}" />
  • Related