VariableMultiValueConverter

El VariableMultiValueConverter es un convertidor que permite a los usuarios convertir los valores de bool mediante un MultiBinding en un único bool. Para ello, les permite especificar si All, Any, None o un número específico de valores son true como se especifica en ConditionType.

El Convert método devuelve el proporcionado values convertido a un resultado general bool basado en el ConditionType definido.

El ConvertBack método solo devolverá un resultado si se establece ConditionTypeen MultiBindingCondition.All .

Propiedades de BaseConverter

Las siguientes propiedades se implementan en la clase base: public abstract class BaseConverter

Propiedad Descripción
DefaultConvertReturnValue Valor predeterminado que se devuelve cuando IValueConverter.Convert(object?, Type, object?, CultureInfo?) genera una excepción Exception. Este valor se usa cuando CommunityToolkit.Maui.Options.ShouldSuppressExceptionsInConverters está establecido en true.
DefaultConvertBackReturnValue Valor predeterminado que se devuelve cuando IValueConverter.ConvertBack(object?, Type, object?, CultureInfo?) genera una excepción Exception. Este valor se usa cuando CommunityToolkit.Maui.Options.ShouldSuppressExceptionsInConverters está establecido en true.

Propiedades de ICommunityToolkitValueConverter

Las siguientes propiedades se implementan en :public interface ICommunityToolkitValueConverter

Propiedad Tipo Descripción
DefaultConvertReturnValue object? Valor predeterminado que se devuelve cuando IValueConverter.Convert(object?, Type, object?, CultureInfo?) genera una excepción Exception. Este valor se usa cuando CommunityToolkit.Maui.Options.ShouldSuppressExceptionsInConverters está establecido en true.
DefaultConvertBackReturnValue object? Valor predeterminado que se devuelve cuando IValueConverter.ConvertBack(object?, Type, object?, CultureInfo?) genera una excepción Exception. Este valor se usa cuando CommunityToolkit.Maui.Options.ShouldSuppressExceptionsInConverters está establecido en true.

Syntax

Los siguientes ejemplos muestran cómo hacer que una Label sea invisible cuando al menos 2 de los valores de una MultiBinding se evalúan como verdaderos.

XAML

Incluir el espacio de nombres XAML

Para usar el kit de herramientas en XAML, es necesario agregar el siguiente xmlns a la página o vista:

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

Por lo tanto, lo siguiente:

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

Se modificaría para incluir el xmlns de la siguiente manera:

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

El VariableMultiValueConverter se puede usar de la siguiente manera en 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"
             x:Class="CommunityToolkit.Maui.Sample.Pages.Converters.VariableMultiValueConverterPage">

    <ContentPage.Resources>
        <ResourceDictionary>
            <toolkit:VariableMultiValueConverter 
                x:Key="VariableMultiValueConverter"
                ConditionType="LessThan"
                Count="2" />
        </ResourceDictionary>
    </ContentPage.Resources>

    <Label Text="At least 2 toppings must be selected.">
        <Label.IsVisible>
            <MultiBinding Converter="{StaticResource VariableMultiValueConverter}">
                <Binding Path="IsCheeseSelected" />
                <Binding Path="IsHamSelected" />
                <Binding Path="IsPineappleSelected" />
            </MultiBinding>
        </Label.IsVisible>
    </Label>

</ContentPage>

C#

VariableMultiValueConverter Se puede usar como se indica a continuación en C#:


class VariableMultiValueConverterPage : ContentPage
{
    public VariableMultiValueConverterPage()
    {
        var label = new Label
        {
            Text = "At least 2 toppings must be selected."
        };

        label.SetBinding(
            Label.IsVisibleProperty,
            new MultiBinding
            {
                Converter = new VariableMultiValueConverter
                {
                    ConditionType = MultiBindingCondition.LessThan,
                    Count = 2
                },
                Bindings = new List<BindingBase>
                {
                    new Binding(static (ViewModel vm) => vm.IsCheeseSelected),
                    new Binding(static (ViewModel vm) => vmIsHamSelected),
                    new Binding(static (ViewModel vm) => vmIsPineappleSelected)
                }
            });

        Content = label;
    }
}

Marcado de C#

Nuestro CommunityToolkit.Maui.Markup paquete proporciona una manera mucho más concisa de usar este convertidor en C#.

using CommunityToolkit.Maui.Markup;

class VariableMultiValueConverterPage : ContentPage
{
    public VariableMultiValueConverterPage()
    {
        Content = new Label()
            .Text("At least 2 toppings must be selected.")
            .Bind(
                Label.IsVisibleProperty,
                new List<BindingBase>
                {
                    new Binding(static (ViewModel vm) => vm.IsCheeseSelected),
                    new Binding(static (ViewModel vm) => vm.IsHamSelected),
                    new Binding(static (ViewModel vm) => vm.IsPineappleSelected)
                },
                converter: new VariableMultiValueConverter
                {
                    ConditionType = MultiBindingCondition.LessThan,
                    Count = 2
                });
    }
}

Propiedades

Propiedad Tipo Descripción
Tipo de condición MultiBindingCondition Indica cuántos valores deben estar true fuera de los valores booleanos proporcionados en MultiBinding.
Count int El número de valores que deben ser verdaderos al usar ConditionType de GreaterThan, LessThan o Exact.

MultiBindingCondition

La enumeración MultiBindingCondition define los miembros siguientes:

  • None - Ninguno de los valores debe ser verdadero.
  • All - Todos los valores deben ser verdaderos.
  • Any - Cualquiera de los valores debe ser verdadero.
  • Exact - El número exacto, tal como está configurado en la propiedad Count, debe ser verdadero.
  • GreaterThan - Debe ser verdadero si es mayor que el número configurado en la propiedad Count.
  • LessThan - Debe ser inferior al número configurado en la propiedad Count para que sea verdadero.

Ejemplos

Puede encontrar un ejemplo de este convertidor en acción en la aplicación de ejemplo .NET MAUI Community Toolkit.

API

Puede encontrar el código fuente de VariableMultiValueConverter en el repositorio .NET MAUI Community Toolkit GitHub.