Search code examples
enumsmaui

MAUI Reading Enum from QueryProperty


I have an enum:

 public enum MediaTypes
 {
     Book = 0,
     Video = 1,
     Magazine = 2,
     Picture = 3
     All = 99
 }

...which I would like to pass to a page and pull off its value as a QueryProperty in the page :

[QueryProperty("MediaType", "MediaType")]
public int MediaType { get; set; }

This works if the type is set to "int", but throws a conversion error if the type is set to what I really want it to be: a MediaTypes.

public MediaTypes MediaType { get; set; }

What's the correct way to pass/parse a QueryProperty which is an enum?


Solution

  • I suppose that "the correct way" is a matter of opinion, but one way for sure to make this work is to have the [QueryProperty] invoke a string-to-MediaTypes converter. You could have it work on either int values or named values if you like as shown.


    Suppose you want a query like this:

    private async void OnNavTestClicked(object sender, EventArgs e)
    {
        await Shell.Current.GoToAsync($"///details?mediatype=book");
    }
    

    ...or like this:

    private async void OnNavTestClickedInt(object sender, EventArgs e)
    {
        await Shell.Current.GoToAsync($"///details?mediatype=99");
    }
    

    Your "some page" class could handle the query like so:

    public enum MediaTypes
    {
        Book = 0,
        Video = 1,
        Magazine = 2,
        Picture = 3,
        All = 99
    }
    [QueryProperty(nameof(MediaTypeQuery), "mediatype")]
    public partial class DetailsPage : ContentPage
    {
        public DetailsPage() => InitializeComponent();
    
        protected override void OnNavigatedTo(NavigatedToEventArgs args)
        {
            base.OnNavigatedTo(args);
            Dispatcher.Dispatch(async ()=> 
                await DisplayAlert("Query Parameter", $"Received ID: {MediaType}", "OK"));
        }
    
        public string MediaTypeQuery
        {
            // Convert int or named value
            set =>
                MediaType = 
                int.TryParse(value, out int n) 
                ? (MediaTypes)n
                : Enum.TryParse(value, ignoreCase: true, out MediaTypes mediaType)
                    ? mediaType
                    : (MediaTypes)(-1); // Default value of your choosing
        }
    
        public MediaTypes MediaType { get; set; }
    }