TechWatching
TechWatching

Reputation: 1549

How to add a switch in Xamarin Shell MenuItem

I want to have a switch in a menuItem of my AppShell.xaml (in addition to the usual text and icon). How can I do that while keeping the styles of the MenuItem ?

I used a DataTemplate in the Shell.MenuItemTemplate of my MenuItem but the result is just ugly as all the styles of the MenuItem are lost. The MenuItem created this way does not have the same font, text color, and font size than the other FlyoutItems and MenuItems of the Shell.

<MenuItem Text="MyMenuItem" Command="{Binding SwitchMode}">
    <Shell.MenuItemTemplate>
        <DataTemplate>
            <StackLayout Orientation="Horizontal" HorizontalOptions="Center">
                <Label Text="{Binding Text}"/>
                <Switch IsToggled="{Binding IsModeActivated}"/>
            </StackLayout>
        </DataTemplate>
    </Shell.MenuItemTemplate>

Upvotes: 3

Views: 1353

Answers (1)

Ben
Ben

Reputation: 2985

Use element Shell.MenuItemTemplate with reference to DataTemplate defined in Resources.

Common/shared element property values can be defined in a "BaseStyle", while menu specific properties can be defined in styles based on the "BaseStyle":

<Shell.Resources>
  ...
  <Style x:Key="labelBaseStyle" TargetType="Label">
    <Setter Property="VerticalTextAlignment" Value="Center" />
  </Style>

  <Style x:Key="firstMenuLabelStyle" TargetType="Label" BasedOn="{StaticResource labelBaseStyle}">
    <Setter Property="FontAttributes" Value="Italic" />
  </Style>

  <Style x:Key="menuLabelStyle" TargetType="Label" BasedOn="{StaticResource labelBaseStyle}">
    <Setter Property="FontAttributes" Value="Bold" />
  </Style>

  <DataTemplate x:Key="firstMenuItemTemplate">
    <StackLayout ...
      <Label Style="{StaticResource firstMenuLabelStyle}" ...
  </DataTemplate>

  <DataTemplate x:Key="menuItemTemplate">
    <StackLayout ...
      <Label Style="{StaticResource menuLabelStyle}" ...
  </DataTemplate>
  ...
</Shell.Resources>
...
<MenuItem Text="MenuItem1" Shell.MenuItemTemplate="{StaticResource firstMenuItemTemplate}" />

<MenuItem Text="MenuItem2" Shell.MenuItemTemplate="{StaticResource menuItemTemplate}" />

Upvotes: 4

Related Questions