Xamarin Forms Tips Part 3: Change Randomly A View’s Color At Run-time

Change Randomly A View's Color
Change Randomly A View’s Color

Hi everyone, here is the third part of the Xamarin Forms Tips series. Today, we will look at how to change a view’s color randomly at run time. I implemented this feature in the “My Expenditures” application. As you can see on the screenshots above, the first letter of the user’s name changes color every time he runs the app. And it does so randomly. This post is all about implementing this functionality.

The app’s name is : My Expenditures. It is available on Play store and Microsoft store. It provides you a smart way to manage you expenses and income. And very detailed stats about how you spend or make money. You can download and use it. You will also find in the app all the features I talk about here.

Change Randomly A View’s Color At Run-time

We will change the color of the text of a label at run-time. This feature is implemented using markup extensions. We predefined a set of colors which we randomly assign to the view. This is extremely simple and here is the code for it.

[ContentProperty("TextColor")]
public class RandomColorExtension : IMarkupExtension
{
    /// <summary>
    /// Send a Random Color to be displayed by the user.
    /// </summary>
    /// <param name="serviceProvider"></param>
    /// <returns></returns>
    public object ProvideValue(IServiceProvider serviceProvider)
    {
        var colors = new List<Color>
        {
            Color.SkyBlue,
            Color.Salmon,
            Color.SandyBrown,
            Color.SeaGreen,
            Color.Turquoise
        };
        
        return colors[new Random().Next(0,4)];
    }
}

After implementing the  markup extension, applying it to a label is very easy.

<Label
                       FontAttributes="Bold"
                       FontSize="{StaticResource ExtraHugeSize}"
                       HorizontalOptions="Center"
                       Text="{Binding UserInitial, Mode=TwoWay}"
                       TextColor="{markupExtensions:RandomColorExtension}"
                       VerticalOptions="Center" />

Conclusion

You can randomly change the color of your controls easily at runtime. This feature can help you improve UX. I applied it to a label, but you could apply it to any other control.

You may be interested by this post about numeric entry recipes. Learn more about markup extensions here.

Follow me on social media and stay updated

Leave a Reply

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