VariableMultiValueConverter

O VariableMultiValueConverter é um conversor que permite aos utilizadores converter bool valores via a MultiBinding para um único bool. Faz isto permitindo que especifiquem se Todos, Qualquer Nenhum ou um número específico de valores são verdadeiros, conforme especificado em ConditionType.

O Convert método devolve o fornecido values convertido num resultado global bool baseado no ConditionType definido.

O ConvertBack método só devolverá um resultado se o ConditionType for definido como MultiBindingCondition.All.

Propriedades do BaseConverter

As seguintes propriedades são implementadas na classe base, public abstract class BaseConverter:

Propriedade Description
DefaultConvertReturnValue Valor padrão a devolver quando IValueConverter.Convert(object?, Type, object?, CultureInfo?) lança um Exception. Este valor é usado quando o CommunityToolkit.Maui.Options.ShouldSuppressExceptionsInConverters está definido como true.
DefaultConvertBackReturnValue Valor padrão a devolver quando IValueConverter.ConvertBack(object?, Type, object?, CultureInfo?) lança um Exception. Este valor é usado quando o CommunityToolkit.Maui.Options.ShouldSuppressExceptionsInConverters está definido como true.

Propriedades do ICommunityToolkitValueConverter

As seguintes propriedades estão implementadas no public interface ICommunityToolkitValueConverter:

Propriedade Tipo Description
DefaultConvertReturnValue object? Valor padrão a devolver quando IValueConverter.Convert(object?, Type, object?, CultureInfo?) lança um Exception. Este valor é usado quando o CommunityToolkit.Maui.Options.ShouldSuppressExceptionsInConverters está definido como true.
DefaultConvertBackReturnValue object? Valor padrão a devolver quando IValueConverter.ConvertBack(object?, Type, object?, CultureInfo?) lança um Exception. Este valor é usado quando o CommunityToolkit.Maui.Options.ShouldSuppressExceptionsInConverters está definido como true.

Syntax

Os exemplos seguintes mostram como tornar um Label invisível quando pelo menos 2 dos valores de um MultiBinding forem verdadeiros.

XAML

Incluindo o namespace XAML

Para usar o kit de ferramentas em XAML, a seguinte xmlns precisa ser adicionada à sua página ou vista.

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

Por conseguinte, o seguinte:

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

Seria modificado para incluir o xmlns da seguinte forma:

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

Utilizar o VariableMultiValueConverter

O VariableMultiValueConverter pode ser utilizado da seguinte forma em 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#

O VariableMultiValueConverter pode ser usado da seguinte forma em 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;
    }
}

Marcação em C#

O nosso CommunityToolkit.Maui.Markup pacote oferece uma forma muito mais concisa de usar este conversor em 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
                });
    }
}

Propriedades

Propriedade Tipo Description
Tipo de condição MultiBindingCondition Indica quantos valores devem estar true fora dos valores booleanos fornecidos no MultiBinding.
Count int O número de valores que devem ser verdadeiros ao usar ConditionType , GreaterThanLessThan ou Exact.

MultiBindingCondition

A MultiBindingCondition enumeração define os seguintes membros:

  • None - Nenhum dos valores deve ser verdadeiro.
  • All - Todos os valores devem ser verdadeiros.
  • Any - Qualquer um dos valores deve ser verdadeiro.
  • Exact - O número exato conforme configurado na Count propriedade deve ser verdadeiro.
  • GreaterThan - Maior do que o número configurado na Count propriedade deve ser verdadeiro.
  • LessThan - Deve ser inferior ao número configurado na propriedade Count.

Exemplos

Pode encontrar um exemplo deste conversor em ação na .NET MAUI Community Toolkit Sample Application.

API

Você pode encontrar o código-fonte para VariableMultiValueConverter no repositório GitHub do .NET MAUI Community Toolkit.