Szerkesztés

Megosztás a következőn keresztül:


EnumToIntConverter

The EnumToIntConverter is a converter that allows you to convert a standard Enum (extending int) to its underlying primitive int type. It is useful when binding a collection of values representing an enumeration type with default numbering to a control such as a Picker.

Note

The ConverterParameter property is required and it should be set to the type of the enum to convert back to, when using a TwoWay or OneWayToSource binding. Otherwise an ArgumentNullException will be thrown. This is to allow for validating whether the int is a valid value in the enum.

For localization purposes or due to other requirements, the enum values often need to be converted to a human-readable string. In this case, when the user selects a value, the resulting SelectedIndex can easily be converted to the underlying enum value without requiring additional work in the associated ViewModel.

BaseConverter Properties

The following properties are implemented in the base class, public abstract class BaseConverter:

Property Description
DefaultConvertReturnValue Default value to return when IValueConverter.Convert(object?, Type, object?, CultureInfo?) throws an Exception. This value is used when CommunityToolkit.Maui.Options.ShouldSuppressExceptionsInConverters is set to true.
DefaultConvertBackReturnValue Default value to return when IValueConverter.ConvertBack(object?, Type, object?, CultureInfo?) throws an Exception. This value is used when CommunityToolkit.Maui.Options.ShouldSuppressExceptionsInConverters is set to true.

ICommunityToolkitValueConverter Properties

The following properties are implemented in the public interface ICommunityToolkitValueConverter:

Property Type Description
DefaultConvertReturnValue object? Default value to return when IValueConverter.Convert(object?, Type, object?, CultureInfo?) throws an Exception. This value is used when CommunityToolkit.Maui.Options.ShouldSuppressExceptionsInConverters is set to true.
DefaultConvertBackReturnValue object? Default value to return when IValueConverter.ConvertBack(object?, Type, object?, CultureInfo?) throws an Exception. This value is used when CommunityToolkit.Maui.Options.ShouldSuppressExceptionsInConverters is set to true.

Syntax

XAML

Including the XAML namespace

In order to use the toolkit in XAML the following xmlns needs to be added into your page or view:

xmlns:toolkit="http://schemas.microsoft.com/dotnet/2022/maui/toolkit"

Therefore the following:

<ContentPage
    x:Class="CommunityToolkit.Maui.Sample.Pages.MyPage"
    xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml">

</ContentPage>

Would be modified to include the xmlns as follows:

<ContentPage
    x:Class="CommunityToolkit.Maui.Sample.Pages.MyPage"
    xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:toolkit="http://schemas.microsoft.com/dotnet/2022/maui/toolkit">

</ContentPage>

Using the EnumToIntConverter

The EnumToIntConverter can be used as follows in XAML:

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:toolkit="http://schemas.microsoft.com/dotnet/2022/maui/toolkit"
	     xmlns:vm="clr-namespace:CommunityToolkit.Maui.Sample.ViewModels.Converters"
             x:Class="MyLittleApp.MainPage">
    <ContentPage.Resources>
         <ResourceDictionary>
             <toolkit:EnumToIntConverter x:Key="EnumToIntConverter" />
         </ResourceDictionary>
    </ContentPage.Resources>

    <VerticalStackLayout Padding="10,10" Spacing="10">
            <Label Text="The EnumToIntConverter is a converter that allows users to convert a standard enum (extending int) to its underlying primitive int type." 
                   TextColor="{StaticResource NormalLabelTextColor}" />
            <Label Text="Selecting a value from the picker will change the enum property in the view model" 
                   TextColor="{StaticResource NormalLabelTextColor}" />
            <Picker ItemsSource="{Binding AllStates}" 
                    SelectedIndex="{Binding SelectedState, Converter={StaticResource EnumToIntConverter}, ConverterParameter={x:Type vm:IssueState}}"
                    TextColor="{StaticResource NormalLabelTextColor}" />
            <Label Text="This label binds to the SelectedIndex property of the picker, both use EnumToIntConverter, so no int properties are necessary in ViewModel"
                   TextColor="{StaticResource NormalLabelTextColor}" />
            <Label Text="{Binding Path=SelectedState, Converter={StaticResource EnumToIntConverter}}" 
                   TextColor="{StaticResource NormalLabelTextColor}" />
        </VerticalStackLayout>
</ContentPage>

C#

The EnumToIntConverter can be used as follows in C#:

class EnumToIntConverterPage : ContentPage
{
    public EnumToIntConverterPage()
    {
      Picker picker = new Picker { Title = "EnumToIntConverter" };
      picker.SetBinding(Picker.ItemsSourceProperty, nameof(ViewModel.AllStates));
      picker.SetBinding(Picker.SelectedItemProperty, nameof(ViewModel.SelectedState));

      Content = new StackLayout
			{
				Margin = new Thickness(20),
				Children = {
					new Label {
						Text = "The EnumToIntConverter is a converter that allows users to convert a standard enum (extending int) to its underlying primitive int type.",
						FontAttributes = FontAttributes.Bold,
						HorizontalOptions = LayoutOptions.Center 
					},
					picker
				}
			};
}

C# Markup

Our CommunityToolkit.Maui.Markup package provides a much more concise way to use this converter in C#.

using CommunityToolkit.Maui.Markup;

class EnumToIntConverterPage : ContentPage
{
    public EnumToIntConverterPage()
    {
        Content = new StackLayout {
          new Picker()
            .Bind(
                Picker.ItemSourceProperty,
                static (ViewModel vm) => vm.AllStates)
            .Bind(
                Picker.SelectedIndexProperty,
                static (ViewModel vm) => vm.SelectedState),

          new Label()
            .Bind(
                Label.TextProperty,
                static (ViewModel vm) => vm.SelectedState,
                converter: new EnumToIntConverter()),
        }
    }
}

Examples

You can find an example of this converter in action in the .NET MAUI Community Toolkit Sample Application.

API

You can find the source code for EnumToIntConverter over on the .NET MAUI Community Toolkit GitHub repository.