Creating A Snack Bar In Xamarin Forms XAML

Snack Bar in Xamarin Forms
Snack Bar in Xamarin Forms

Hello friends, notifying users about what happens in your mobile application is necessary. There is the Snack Bar which is good for this scenario. But in Xamarin.Forms by default, you don’t have the ability to call snack bar. Though by default you can’t do this, it is possible to make a Snack Bar in Xamarin Forms XAML exclusively. Without any platform specific code. This post is all about implementing this. Let’s dive in.

Here is the source code for the simple app built in this post.

Let’s Build the Snack Bar in Xamarin Forms

The implementation of this control is very simple. With a Templated view, we will create a simple control, design the snack bar’s UI with XAML and add appropriate Bindable properties.

The Snack Bar’s Look With XAML

When you look at a snack bar, it is pretty simple. A text field and a button. The button has only simple functions like close, cancel… So with the Templated View, adding these controls and the appropriate bindable properties to have the behavior of Android’s original snack bar will do it.

<TemplatedView xmlns="http://xamarin.com/schemas/2014/forms" 
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="Xamarin.FormsSnackBarDemo.SnackBar">
    <TemplatedView.ControlTemplate>
        <ControlTemplate>
            <Grid>
                <Label Text="{TemplateBinding Message}"
                       VerticalOptions="Center" HorizontalOptions="FillAndExpand"
                       Margin="20, 5, 5, 5" LineBreakMode="WordWrap"
                       FontSize="{TemplateBinding FontSize}"
                       TextColor="{TemplateBinding TextColor}"
                       FontFamily="{TemplateBinding FontFamily}"/>

                <Button Grid.Column="1" HorizontalOptions="End"
                        Clicked="CloseButton_Clicked" Margin="2"
                        FontFamily="{TemplateBinding FontFamily}"
                        FontSize="{TemplateBinding FontSisze}"
                        TextColor="{TemplateBinding ButtonTextColor}"
                        BackgroundColor="{TemplateBinding CloseButtonBackGroundColor}"
                        VerticalOptions="Center" Text="{TemplateBinding CloseButtonText}"/>
            </Grid>
        </ControlTemplate>
    </TemplatedView.ControlTemplate>
</TemplatedView>

Now, for the snack bar in Xamarin.Forms to behave as a snack bar, and be a reusable control, we need to add properties which are bindable. These properties include the The message, text color, background color, font size, button text color and so on. Here are some properties I added, you could add more if you wish.

public static readonly BindableProperty ButtonTextColorProperty = BindableProperty.Create("ButtonTextColor", typeof(Color), typeof(SnackBar), default(Color));
        public Color ButtonTextColor
        {
            get { return (Color)GetValue(ButtonTextColorProperty); }
            set { SetValue(ButtonTextColorProperty, value); }
        }

        public static readonly BindableProperty MessageProperty = BindableProperty.Create("Message", typeof(string), typeof(SnackBar), default(string));
        public string Message
        {
            get { return (string)GetValue(MessageProperty); }
            set { SetValue(MessageProperty, value); }
        }

        public static readonly BindableProperty CloseButtonTextProperty = BindableProperty.Create("CloseButtonText", typeof(string), typeof(SnackBar), "Close");
        public string CloseButtonText
        {
            get { return (string)GetValue(CloseButtonTextProperty); }
            set { SetValue(CloseButtonTextProperty, value); }
        }

        public static readonly BindableProperty FontSizeProperty = BindableProperty.Create("FontSize", typeof(float), typeof(SnackBar), default(float));
        public float FontSize
        {
            get { return (float)GetValue(FontSizeProperty); }
            set { SetValue(FontSizeProperty, value); }
        }

Opening and Closing the Snack Bar With Animations

A snack bar is supposed to appear at the bottom of the app’s user interface. It should appear with an animation moving it from the bottom to a position where it will be visible to the user. We will do this with a Bindable property called IsOpen. This property will cause an animation when changed, and cause the snack bar to show or hide its self. Here is the code to accomplish this.

public static readonly BindableProperty IsOpenProperty = BindableProperty.Create("IsOpen", typeof(bool), typeof(SnackBar), false, propertyChanged: IsOpenChanged);
        public bool IsOpen
        {
            get { return (bool)GetValue(IsOpenProperty); }
            set { SetValue(IsOpenProperty, value); }
        }

        private static void IsOpenChanged(BindableObject bindable, object oldValue, object newValue)
        {
            bool isOpen;

            if (bindable != null && newValue != null)
            {
                var control = (SnackBar)bindable;
                isOpen = (bool)newValue;

                if (control.IsOpen == false)
                {
                    control.Close();
                }
                else
                {
                    control.Open(control.Message);
                }
            }
        }

To animate the opening and closing of our snack bar control, we use Xamarin Forms animations. Specifically, the Translate animation to move the control upward and downward when needed. And at a particular speed. Here is how we do it.

public async void Close()
        {
            await this.TranslateTo(0, 50, AnimationDuration);
            Message = string.Empty;
            IsOpen = IsVisible = false;
        }

        public async void Open(string message)
        {
            IsVisible = true;
            Message = message;
            await this.TranslateTo(0, 0, AnimationDuration);
        }

Using the Xamarin Forms Snack Bar

To use this control as a typical snack bar, it is important to note that its placement and the container in which it is used will affect its look and feel. In this example, we will place it in a Grid, at the bottom. That is, setting its VerticalOptions property to End. But if it was placed in a StackLayout for example, it would behave differently. So here is it.

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:Xamarin.FormsSnackBarDemo"
             x:Class="Xamarin.FormsSnackBarDemo.MainPage">

    <ContentPage.Content>
        <Grid>
            <Button Text="Click Me" Clicked="Button_Clicked"
                    HorizontalOptions="Center"
                    VerticalOptions="Center"/>

            <local:SnackBar  x:Name="SnackB" HeightRequest="50" FontSize="{OnPlatform iOS=12, Android=13, UWP=15}" 
                             BackgroundColor="#323232" 
                             TextColor="White"
                             IsOpen="False"
                             VerticalOptions="End"
                             Message="I'm a snack bar... I love showing my self."
                             ButtonTextColor="Orange"
                             CloseButtonText="Exit"/>
        </Grid>
    </ContentPage.Content>

</ContentPage>
Snack Bar in Xamarin Forms Demo
Snack Bar in Xamarin Forms Demo

Conclusion

With this, we have built a Snack Bar in Xamarin Forms. This control is not a native implementation and sure is an easier implementation. If need be, you could add additional properties. Or even more buttons, all that in XAML without any platform specific code.
Here is the source code for the simple app built in this post.

If you liked this post, or it was useful to you, please¬†ūüĎ欆like it, share it on twitter, facebook or other social media‚Ķ in case you want to get updated on any new useful post, follow me on¬†twitter,¬†¬†Github¬† and like my page on¬†facebook. And every other social media by clicking on the¬† buttons at the end of this post.Follow me on social media and stay updated

Follow me on social media and stay updated

4 Replies to “Creating A Snack Bar In Xamarin Forms XAML”

  1. Good post!
    But may I know why did you use TemplatedView instead of ContentView for example? is there any pros. TemplatedView is nicer in WPF where it’s possible to really modify any UI element, but in X.F it’s just a container, like any View element?

  2. No big reason for doing that, Using a Templated view hinder’s the user from deleting the control’s content since it doesn’t have a content property whereas the ContentView has that property. instead, the templated view uses a template for its display, this template can just be changed.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.