Condividi tramite


EnumToIntConverter

EnumToIntConverter è un convertitore che consente di convertire uno standard Enum (estendendo int) nel tipo primitivo sottostanteint. È utile quando si associa una raccolta di valori che rappresentano un tipo di enumerazione con numerazione predefinita a un controllo, ad esempio .Picker

Nota

La ConverterParameter proprietà è obbligatoria e deve essere impostata sul tipo dell'enumerazione in cui eseguire la conversione quando si usa un'associazione TwoWay o OneWayToSource . In caso contrario, verrà generata un'eccezione ArgumentNullException . Ciò consente di convalidare se è int un valore valido nell'enumerazione .

Ai fini della localizzazione o a causa di altri requisiti, i valori di enumerazione spesso devono essere convertiti in una stringa leggibile dall'utente. In questo caso, quando l'utente seleziona un valore, il risultato SelectedIndex può essere facilmente convertito nel valore sottostante enum senza richiedere ulteriori operazioni nel ViewModel associato.

Proprietà BaseConverter

Le proprietà seguenti vengono implementate nella classe base : public abstract class BaseConverter

Proprietà Descrizione
DefaultConvertReturnValue Valore predefinito da restituire quando IValueConverter.Convert(object?, Type, object?, CultureInfo?) genera un'eccezione Exception. Questo valore viene usato quando CommunityToolkit.Maui.Options.ShouldSuppressExceptionsInConverters è impostato su true.
DefaultConvertBackReturnValue Valore predefinito da restituire quando IValueConverter.ConvertBack(object?, Type, object?, CultureInfo?) genera un'eccezione Exception. Questo valore viene usato quando CommunityToolkit.Maui.Options.ShouldSuppressExceptionsInConverters è impostato su true.

Proprietà ICommunityToolkitValueConverter

Le proprietà seguenti vengono implementate in public interface ICommunityToolkitValueConverter:

Proprietà Type Descrizione
DefaultConvertReturnValue object? Valore predefinito da restituire quando IValueConverter.Convert(object?, Type, object?, CultureInfo?) genera un'eccezione Exception. Questo valore viene usato quando CommunityToolkit.Maui.Options.ShouldSuppressExceptionsInConverters è impostato su true.
DefaultConvertBackReturnValue object? Valore predefinito da restituire quando IValueConverter.ConvertBack(object?, Type, object?, CultureInfo?) genera un'eccezione Exception. Questo valore viene usato quando CommunityToolkit.Maui.Options.ShouldSuppressExceptionsInConverters è impostato su true.

Sintassi

XAML

Inclusione dello spazio dei nomi XAML

Per usare il toolkit in XAML, è necessario aggiungere le informazioni seguenti xmlns nella pagina o nella visualizzazione:

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

Di conseguenza:

<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>

Verrà modificato in modo da includere l'oggetto xmlns come indicato di seguito:

<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>

Uso di EnumToIntConverter

Può EnumToIntConverter essere usato come segue 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#

Può EnumToIntConverter essere usato come indicato di seguito in C#:

class EnumToIntConverterPage : ContentPage
{
    public EnumToIntConverterPage()
    {
        Picker picker = new Picker { Title = "EnumToIntConverter" };
        picker.SetBinding(Picker.ItemsSourceProperty, static (ViewModel vm) => vm .AllStates);
        picker.SetBinding(Picker.SelectedItemProperty, static (ViewModel vm) => vm.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

Il CommunityToolkit.Maui.Markup pacchetto offre un modo molto più conciso per usare questo convertitore 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()),
        }
    }
}

Esempi

È possibile trovare un esempio di questo convertitore in azione nell'applicazione di esempio .NET MAUI Community Toolkit.

API

È possibile trovare il codice sorgente per EnumToIntConverter over nel repository GitHub di .NET MAUI Community Toolkit.