Create a time zone selection control for .NET MAUI (2023)

This article is part of thatMaui UI JulyA community series of blog posts and videos hosted by Matt Goldman. Be sure to check out the other posts in this series!

Hello, my name is Matt Johnson Pints. I recently joined Sentry as a working engineerSentry .NET-SDK.One of my first big projects was raising theFixed .NET, now westart preview.Come on, tried!

I'm also a time zone nerd. Yes, I jumped in while others shouted to avoid the problem. If you've ever asked a technical question about time zones on the internet, chances are we've met. Ah yes - time zones. They are absolutely essential to our modern world, but they can be a pain to deal with - especially for software developers! Most of our platforms and languages ​​include features to handle time zones, but sometimes a better understanding is required to use these features properly. When it comes to cross-platform mobile development, such as offering .NET MAUI, it can be very difficult to provide a consistent experience.

So what does Sentinel have to do with time zones? Well, not much, but now that I'm a .NET MAUI developer, I thought it would be fun to contribute some open source stuff! For your enjoyment I have created a free oneMAUI time zone dialer control, which provides a consistent cross-platform user experience for selecting a time zone from a list. You can use it anywhere (and in any time zone)! Maybe you're building an event planning app? I bet you have to choose a time zone for your event.

For the record, the sample app included in the project also uses theSentinel .NET MAUI-SDK.If the sample app crashes on your device, I'll know automatically! Hopefully this means I'll be improving this control over time to make it even better.

In this blog post I will show you how I put together the MAUI time zone dialer controls. My goal is to teach you about time zones and hopefully give you some insight into writing custom UI controls for .NET MAUI.

What's so hard about time zones?

One of the biggest challenges with time zones isidentify them. Ask someone what their time zone is and you'll probably get several answers, such as "Central Time," "Central Standard Time," "Central Daylight Saving Time," or "Chicago Time." You may receive an abbreviation such as "CST", "CDT", or "CT". Sometimes you get a value like "UTC-6", "GMT-6", "UTC-06:00", "UTC-5", "GMT-5" or "UTC-05:00". All of these are used for the third official time zone of the United States (yes,thirdSome of these names are valid all the time, while others are only valid during certain times of the year. This is only one time zone on Earth, and it's insideEngels.Usually time zone names and abbreviations are localized. If you speak French, you're probably calling in the same time zone"Central Standard Time"and abbreviate it as "HNC".

Time zone abbreviations are also very confusing because the world is big and there are many countries that start with the same letter. Therefore, if you simply state a time zone as "CST", without any additional context, there is no way to know if it refers to "Central Standard Time", "Cuba Standard Time", or "China Standard Time".

To solve this problem in the calculations, we use the time zoneID the past there were different sets of timezone identifiers, but they have mostly been merged and we use them nowIANA time zone databaseIn almost every programming language, platform and operating system. Even Microsoft Windows (which used to just use their own set of identifiers) has started using IANA so you can use them in .NET. The IANA time zone IDs for the above regions are "America/ChicagoIt is an exact string that can be used as an identifier on all platforms and is never translated.

This is where we get to the fun part. Do we really want to show our users the IANA time zone ID? What if they only know Japanese? How would English strings help them? While you may have seen some applications provide a list of these strings for the user to choose from, this is not the recommended approach. In fact, the recommendation of the IANA time zone administrators is that you shouldNeeshown to the user. Instead, the string displayed to the user must come from another source, such asUnicode Common Locale data repository(CLDR).

So let's create a time zone selector that will be displayedUnicodestring, each supported by the corresponding IANA time zone ID. We also provide each with a location and current UTC offset to help users make their choice. We want it to be a scrollable list like this:

(Video) .NET MAUI - Building your own custom controls

Create a time zone selection control for .NET MAUI (1)

Note that this is a very rough first try - I have lots of ideas to make it better over time!

Create a .NET MAUI control project

I assume you already have a development environment set up to use MAUI. If not, check MicrosoftStart itContinue with the previous document.

The first step in our journey is to create a new .NET project. Since this is a reusable component, I will create a MAUI class library. I also want to sample a MAUI app and test project and link them together.

mkdir MauiTimeZonePickercd MauiTimeZonePicker dotnet néo mauilib -n MauiTimeZonePicker -o srcdotnet néo maui -n MauiTimeZonePickerSampleApp -o sampledotnet néo xunit -n MauiTimeZonePicker voeg testreftT toe.

Note that you may want to delete the sln file created in the examples folder and create a new file in the root folder.

Now I can fire up VS Code and start editing. You can also use Visual Studio, VS for Mac, or JetBrains Rider, but you'll need the latest sample version of each tool to use MAUI. For this blog post, I'll stick with the command line and VS Code.

Create controls and their elements

We're going to create a new control, but we don't want to start from scratch. Instead, we start with a layout so we can add other elements to it. There are manylay-out typeusable. To match our design, we will useverticale stapellay-out, it just puts each element on top of each other.

Namespaces Maui time zone selector;People class time zone selector : verticale stapellay-out{}

Next, we'll add some content to the layout. FirstInscriptionbefore the title, after theLimitationfor the box below. Within the boundaries we place oneview collectioncontrol, which will do most of the heavy lifting of displaying the list of time zones.

use Microsoft.Maui.control.form;Namespaces Maui time zone selector;People class time zone selector : verticale stapellay-out{ People time zone selector() { add content(); } private vacuum add content() { Add to(jong Inscription {text= "Select time zone...",lettertypegrootte= 14 }); Add to(jong Limitation {blow shape= jong rectangle(),stuffing= 2,contents= Download the collection view() }); } private view collection Download the collection view() { it wasdisplay= jong view collection { // Itembron = ALLES, //project template = ALL,Maximum required height= 200,fashion selection=fashion selection.single}; ((LinearItemsLayout)display.layout of the project).distance from objects= 10; YIELDdisplay; }}
(Video) .NET MAUI Controls: Mastering the Basics and Beyond

One important "pitfall" to point out: if you're using a boundary checker, make sure you set up the StrokeShape. Otherwise, you will not only have the border, but also the internal contentinvisibleWhen viewed on iOS and macCatalyst. This may be a bug in MAUI, but it's easy to find.

Next we want to create an element template for our control and give it some elements to render! You can see the full template I'm using in the source code repositoryhere.

Retrieve time zone resource information

Creating the controls seems simple enough so far - but where does the data come from? We can try to usetime zone informationobject, but we'll find that it doesn't necessarily have all the local strings we need. As mentioned earlier, we expect most of our data to come from the CLDR project on Unicode. Well, it turns out that this data is already available on all the platforms we use - mostly through platform-specific Unicode appsICLibraries (international components of Unicode), distributed by the operating system.

Because .NET MAUI has great call supportplatformspecifieke code, let's use it.

  • On Android we have accessICU application from Android.Android exposes Java classes, while .NET uses MAUI C# inAndroid.IcuNamespaces.

  • In iOS and macCatalyst, we have access to Apple Foundation classes that have behind-the-scenes access to IANA and ICU data, includingNS time zone,NSlocale, InNSDateFormatter.These are also available through C# inbaseNamespaces.

  • In Windows, we have accessICUs supported by WindowsVia C api only. However, we can still access it through our .NET MAUI codep/bel.These can get a little complicated, butICU4C API referenceCome to handy. Note that we can only call the C API - not C++.

If you want to delve into this, check out theTime zone resource providerView the lessonsource code repositoryIt is important to note that there are many different implementations of the same method for specific platforms. Thank you Maui!

Once we have the data, we can create methods to access it and call those methods from our control. The details don't really matter here, it's enough to show the end resultelement broncollection overview of . i designed mineTime zone resource providergive listtime zone sourceobjects, each of which has different information needed to represent and use a particular time zone.

response event

we are not enoughprojectionA list from which we also need to allow the user to select an item. After making that choice, we may need to take action. Most of these are achieved through our useview collectioncontrol, but we need to expose it to the user. I also expose the collection view itself so we can set other properties if needed.

People view collectionview collection{ I get; }People time zone source;selected item=>view collection.selected itemif time zone source;People Event event handler<SelectedItemChangedEventArgs>;The selected item has been changed;People class SelectedItemChangedEventArgs : event parameters{ People SelectedItemChangedEventArgs(time zone source;previous choice, time zone source;current selection) {previous choice=previous choice;current selection=current selection; } People time zone source;previous choice{ I get; } People time zone source;current selection{ I get; }}
(Video) Reusable Controls and Data Template Selectors in Xamarin.Forms & .NET MAUI

We can outsource collection viewingsthe selection has been changedWhen we create control, our own events.

display.the selection has been changed+= (_,parameter) =>{ it wasprevious choice=parameter.previous choice.priority or default() if time zone source; it wascurrent selection=parameter.current selection.priority or default() if time zone source; it wasevent parameters= jong SelectedItemChangedEventArgs(previous choice,current selection);The selected item has been changed;.TRANSPORT(It,event parameters);};

Now users will have an intense typing experiencethe selection has been changedevents andselected itemproperty in our TimeZonePicker.

Use our controls in your app

Now that we've created our control, we can use it in our application. Well - you've probably gotten to this point before, because it's hard to get there without trying to check it out a few times along the way. Anyway, here's how you add it:

In your application, refer to the class library project that contains the custom control and support code. we have usedadd point netcommand before, but you can also add project references via Visual Studio or edit the csproj file directly to addprojectrapportInscription.

<Work team> <projectrapport Involving="..\src\MauiTimeZonePicker.csproj" />Work team>

Your end users dopackage reportlabel instead. For example, if you want to test my current app:

<Work team> <package report Involving="mjp.MauiTimeZonePicker" Version="0.1.0 preview" />Work team>

Now add a package reference toMaui sentinel.wait, kidding! You don't have to use guards if you don't want to. But it's easy if you do the following:

<package report Involving="Maui sentinel" Version="3.19.0-preview.2" />

Finally add. Let's add the controls to your app! Assuming you're in XAML, you'll need to enter a namespace and give it an alias.

(Video) Getting Started with the .NET MAUI DateTime Range Selector


You can then add the control anywhere in your application. I also named and leveraged the event we created.

<mjp:time zone selector X:Name="time zone selector" The selected item has been changed="the time zone has been changed" />

Sure, you might want your app to do a lot of other things, but when it comes to using controls, it's pretty straightforward.

Yes, it works

This is what the final sample app looks like on my Android emulator.

Create a time zone selection control for .NET MAUI (2)

check out other platformsScreenshot from the README repository.


It would be great if we could add some unit tests to this project. Unfortunately, most of the code that actually needs to be tested is platform specific. To verify this, unit tests must be performed on the device. Currently this is a challenge for MAUI developers.

We have that too at SentrySentry.Maui same problem, so we started working on it. We also recently learned that there is oneXunit.Runners.MauiThe project is under development. Hopefully we can join forces and find a solution that everyone can use (including the time zone selector)!

final thoughts

.NET MAUI is beautiful. I absolutely love using it. Xamarin laid the groundwork and still provides much of the basic foundation of how MAUI works, but MAUI is simpler. I especially like that it uses the same modern .NET toolchain that I use today when I write everything else.

I will keep repeating this MAUI time zone selection project. Who knows, someone might find it useful and it will become super popular. comeJoin me on GitHubIf you want to join. I like to give feedback and input. I'm glad to have custom controls to play with and would love to work on this with you.

(Video) How To Create Custom Picker Control (Dropdown Button) In .NET MAUI

don't forget to tryAll guards for .NETNeeds for bug tracking and performance monitoring. Our .NET MAUI SDK is brand new, but we have many other satisfied .NET customers using our product.

If you liked this article, feel free to contact me on Twitter:@mattjohnsonpint.Thank you!


What is the class used to create a screen in .NET Maui? ›

A . NET MAUI page generally occupies the full screen or window. The page usually contains a layout, which contains views and possibly other layouts. Pages, layouts, and views derive from the VisualElement class.

What is the context menu in Dotnet Maui? ›

A context menu, often known as a right-click menu, offers contextual commands that are specific to the control being clicked on. In . NET Multi-platform App UI (. NET MAUI), a context menu can be added to any control that derives from Element, on Mac Catalyst and Windows.

Is .NET MAUI worth learning? ›

If you need a cross-platform UI solution that can run on any or all of Android, iOS, Mac, Windows, and potentially the Web, and you're prepared for a bit of a bumpy ride then I would say absolutely yes.

Is .NET MAUI same as xamarin? ›

NET MAUI is an evolution of Xamarin. Forms, they have most of their features in common. You can get almost all things in . NET MAUI that Xamarin has, like controls, layouts, Shell, gestures, templates, and cross-platform APIs for device features.

How do I set context menu? ›

Type regedit and press Enter. You should see a value named MenuDropAlignment in the right pane (If it doesn't exist, create a new string value named MenuDropAlignment). Double-click on it to modify. In order to make context menu open to the right side, type 0 in the Value data field and click OK.

How to set up .NET MAUI? ›

Create your app

Create a new .NET MAUI app: Open Visual Studio 2022. Select the Create a new project button. In the Create a new project window, select MAUI from the All project types drop-down, select the .NET MAUI App template, and then click the Next button.

How do I call API in .NET MAUI? ›

To call a protected API, your . NET MAUI application needs to make a request by including a valid access token in the Authorization header. So, the first step is to request an access token from Auth0 that enables the application to call the ASP.NET Core Web API you registered earlier.

Is NET MAUI better than Flutter? ›

NET MAUI uses native UI components to render its user interface, while Flutter uses its custom rendering engine to draw UI components. This means that . NET MAUI applications may have a more consistent native look and feel, while Flutter applications may have a more unique appearance that can be easily customized.

Why Maui is better than Xamarin? ›

Greater performance: Since it uses less memory and CPU than Xamarin Forms, there will be better performance overall. Building native UI: By leveraging the same platform-specific code as other platforms, such as Android or iOS, you may generate the same look and feel for your application.

Is .NET MAUI easy to use? ›

NET MAUI application runs on any machine like windows or android emulator. It provides a variety of controls and widgets, and it's easy to use; you can get started with just a few lines of code. It is a set of libraries and tools that make it easy to create . NET cross-platform applications.

Is .NET MAUI a replacement for WPF? ›

NET MAUI is an extension of what was Xamarin Forms, you can write a single piece of C# code that will run on Windows, Mac, Android, and iOS. Another big benefit of using MAUI is that you are effectively writing code in WPF (Windows Presentation Foundation). MAUI isn't WPF, but it is close.

Is .NET MAUI ready for production? ›

NET MAUI (Multi-platform App UI) has been introduced first in May 2020 during the annual Microsoft Build Conference. Two years later, it is announced production-ready by Microsoft at the same event.

How stable is .NET MAUI? ›

It's pretty stable when you eventually get everything to work. But the way there haven't been worth it. You'll need to do workarounds for the known bugs. As I've used to be a Xamarin dev I can tell MAUI won't be stable for a year.

What is the key code for context menu? ›

Of course, if you're ever stuck without a mouse, and you need to open the context menu, this good key will come in handy. If a keyboard doesn't have it, don't forget about the Shift + F10 or Ctrl + Shift + F10 hotkey as alternatives.

How do I get the full context menu? ›

To bring back the classic context menu on Windows 11, use these steps:
  1. Open Start on Windows 11.
  2. Search for regedit and click the top result to open the Registry.
  3. Navigate to the following path: HKEY_CURRENT_USER\SOFTWARE\CLASSES\CLSID.
  4. Right-click the CLSID key, select the New menu, and select the Key option.
Feb 15, 2023

What key is context menu? ›

The shortcut, for those who have not discovered it, is Shift-F10.

What are the prerequisites for .NET MAUI? ›

NET MAUI) apps can be written for the following platforms:
  • Android 5.0 (API 21) or higher.
  • iOS 11 or higher, using the latest release of Xcode.
  • macOS 10.15 or higher, using Mac Catalyst.
  • Windows 11 and Windows 10 version 1809 or higher, using Windows UI Library (WinUI) 3.

Can .NET MAUI run in browser? ›

NET Multi-platform App UI (. NET MAUI) IBrowser interface. This interface enables an application to open a web link in the system-preferred browser or the external browser.

Does .NET MAUI use C#? ›

. NET MAUI (. NET Multi-platform App UI) is a framework for building modern, multi-platform, natively compiled iOS, Android, macOS, Windows and apps using C# and XAML in a single codebase.

How do I call my own API? ›

How to Do API Testing
  1. Enter the URL of the API endpoint. ...
  2. Select the appropriate HTTP method. ...
  3. Enter your credentials in the Authorization tab. ...
  4. Click Send to submit your API request.
Sep 20, 2021

How to call Web API in .NET MVC? ›

Consuming Web API
  1. Create ASP.NET MVC Project.
  2. Add MemberViewModel.
  3. Add Microsoft.AspNet.webApi.Client from the NuGet library.
  4. Code for consuming the Web API.
  5. Run the project and call action method on URL.
Jan 8, 2021

How do I call API and get data? ›

The most straightforward way of accessing data from an API endpoint is simply viewing it in the browser. As long as you're connected to the internet, you should be able to preview most API's data regardless of its format.

Does Maui use HTML? ›

NET Multi-platform App UI (. NET MAUI) WebView displays remote web pages, local HTML files, and HTML strings, in an app. The content displayed a WebView includes support for Cascading Style Sheets (CSS), and JavaScript.

How do I create a new .NET MAUI project? ›

Create a new .NET MAUI app:
  1. Open Visual Studio 2022.
  2. Select the Create a new project button.
  3. In the Create a new project window, select MAUI from the All project types drop-down, select the .NET MAUI App template, and then click the Next button.

How do I create a .NET MAUI project? ›

Create an app
  1. Launch Visual Studio 2022. ...
  2. In the Create a new project window, select MAUI in the All project types drop-down, select the . ...
  3. In the Configure your new project window, name your project, choose a suitable location for it, and click the Next button:
Apr 11, 2023

Can .NET MAUI make web apps? ›

Learn how to use .NET MAUI to build apps that run on mobile devices and on the desktop using C# and Visual Studio. You'll learn the fundamentals of building an app with .NET MAUI and more advanced topics such as local data storage and invoking REST-based web services.

Does .NET MAUI use CSS? ›

NET Multi-platform App UI (. NET MAUI) apps can be styled using Cascading Style Sheets (CSS).

Can .NET MAUI run on web? ›

NET MAUI does not support web but “developers can utilize the Blazor framework to provide a bridge to use MAUI resources.

Is .NET MAUI free? ›

NET MAUI component suite. All DevExpress . NET MAUI controls listed on this webpage are available free-of-charge.

Is .NET MAUI available in Visual Studio? ›

Create a new project in visual studio 2022 and select app option under the multiplatform on the left side and after that, you need to click . NET MAUI App with C# option and click continue button. On the next page, you need to select the . Net framework version 6.0 and click continue button.

Is Maui just Xamarin? ›

Using .NET MAUI, you can develop apps that can run on Android, iOS, macOS, and Windows from a single shared code-base. .NET MAUI is open-source and is the evolution of Xamarin.Forms, extended from mobile to desktop scenarios, with UI controls rebuilt from the ground up for performance and extensibility.

Is .NET MAUI fully released? ›

On May 23, 2022 the . NET Multi-platform App UI, or . NET MAUI, was released to general availability. . NET MAUI gives you a first-class, cross-platform UI stack targeting Android, iOS, macOS, and Windows.


1. Creating Horizontal Calendar Control In .NET MAUI
(Programming With Pragnesh)
2. Drawn controls in .NET MAUI
3. Getting Started with the .NET MAUI DataGrid Control
(Syncfusion, Inc)
4. .NET MAUI Tutorial Full Course
(Derek Banas)
5. BindableLayout: Repeater Control for all! With Xamarin.Forms and .NET MAUI
(Gerald Versluis)
6. Setup Your .NET MAUI Dev Environment - .NET Maui Crash Course #1
(Gerald Versluis)


Top Articles
Latest Posts
Article information

Author: Fr. Dewey Fisher

Last Updated: 10/01/2023

Views: 5269

Rating: 4.1 / 5 (62 voted)

Reviews: 85% of readers found this page helpful

Author information

Name: Fr. Dewey Fisher

Birthday: 1993-03-26

Address: 917 Hyun Views, Rogahnmouth, KY 91013-8827

Phone: +5938540192553

Job: Administration Developer

Hobby: Embroidery, Horseback riding, Juggling, Urban exploration, Skiing, Cycling, Handball

Introduction: My name is Fr. Dewey Fisher, I am a powerful, open, faithful, combative, spotless, faithful, fair person who loves writing and wants to share my knowledge and understanding with you.