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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | [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.
1 2 3 4 5 6 7 | <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