Observação
O acesso a essa página exige autorização. Você pode tentar entrar ou alterar diretórios.
O acesso a essa página exige autorização. Você pode tentar alterar os diretórios.
O VariableMultiValueConverter é um conversor que permite que os usuários convertam valores bool por meio de uma MultiBinding em um único bool. O conversor faz isso permitindo que especifiquem se Todos, Quaisquer, Nenhum ou um número específico de valores são true, conforme especificado em ConditionType.
O método Convert retorna os values fornecidos convertidos em um resultado bool total baseado na ConditionType definida.
O método ConvertBack só retornará um resultado se o ConditionType estiver definido como MultiBindingCondition.All.
Propriedades do BaseConverter
As seguintes propriedades são implementadas na classe base, public abstract class BaseConverter:
| Propriedade | Descrição |
|---|---|
DefaultConvertReturnValue |
Valor padrão a ser retornado quando IValueConverter.Convert(object?, Type, object?, CultureInfo?) gera uma Exception. Esse valor é usado quando CommunityToolkit.Maui.Options.ShouldSuppressExceptionsInConverters é definido como true. |
DefaultConvertBackReturnValue |
Valor padrão a ser retornado quando IValueConverter.ConvertBack(object?, Type, object?, CultureInfo?) gera uma Exception. Esse valor é usado quando CommunityToolkit.Maui.Options.ShouldSuppressExceptionsInConverters é definido como true. |
Propriedades do ICommunityToolkitValueConverter
As seguintes propriedades são implementadas no public interface ICommunityToolkitValueConverter:
| Propriedade | Type | Descrição |
|---|---|---|
DefaultConvertReturnValue |
object? |
Valor padrão a ser retornado quando IValueConverter.Convert(object?, Type, object?, CultureInfo?) gera uma Exception. Esse valor é usado quando CommunityToolkit.Maui.Options.ShouldSuppressExceptionsInConverters é definido como true. |
DefaultConvertBackReturnValue |
object? |
Valor padrão a ser retornado quando IValueConverter.ConvertBack(object?, Type, object?, CultureInfo?) gera uma Exception. Esse valor é usado quando CommunityToolkit.Maui.Options.ShouldSuppressExceptionsInConverters é definido como true. |
Sintaxe
Os exemplos a seguir mostram como tornar um Label invisível quando pelo menos 2 dos valores em uma MultiBinding são avaliados como true.
XAML
Incluir o namespace XAML
Para usar o kit de ferramentas no XAML, o xmlns a seguir precisa ser adicionado à sua página ou exibição:
xmlns:toolkit="http://schemas.microsoft.com/dotnet/2022/maui/toolkit"
Portanto, 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 conforme 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"
xmlns:toolkit="http://schemas.microsoft.com/dotnet/2022/maui/toolkit">
</ContentPage>
Como usar o VariableMultiValueConverter
O VariableMultiValueConverter pode ser usado da seguinte maneira 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 maneira 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;
}
}
Markup do C#
Nosso pacote do CommunityToolkit.Maui.Markup fornece uma maneira muito mais concisa de usar esse conversor no 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 | Type | Descrição |
|---|---|---|
| ConditionType | MultiBindingCondition |
Indica quantos valores devem ser true entre os valores boolianos fornecidos na MultiBinding. |
| Count | int |
O número de valores que devem ser definidos como true ao usar ConditionType de GreaterThan, LessThan ou Exact. |
MultiBindingCondition
A enumeração MultiBindingCondition define os seguintes membros:
None— Nenhum dos valores deve ser true.All— Todos os valores devem ser true.Any— Qualquer um dos valores deve ser true.Exact— O número exato, conforme configurado na propriedadeCount, deve ser true.GreaterThan— Um número maior do que o número configurado na propriedadeCountdeve ser true.LessThan— Um número menor que o número configurado na propriedadeCountdeve ser true.
Exemplos
Você pode encontrar um exemplo desse conversor em ação na Amostra de aplicativo do Kit de Ferramentas da Comunidade do .NET MAUI.
API
O código-fonte do VariableMultiValueConverter pode ser encontrado no repositório GitHub do .NET MAUI Community Toolkit.
.NET MAUI Community Toolkit