El art铆culo presenta enfoques generalizados para usar al escribir XAML-code.

IValueConverterData BindingXAMLWPFUWPXamarin FormsUISwitchConverterKeyToValueConverterInlineConverterAggregateConverterResourceDictionary
junto con el motor de enlace de datos son componentes importantes en el desarrollo de interfaces de usuario basadas en XAML. Los convertidores de valor implican la presencia de l贸gica en una clase separada que implementa la interfaz IValueConverter. Normalmente, el nombre de la clase refleja el prop贸sito funcional y las propias instancias se declaran en el marcado.
Conversor de conmutadores y conversor de clave a valor
En la pr谩ctica, muchos convertidores tienen valores l贸gicos triviales similares en estructura a (?:) o dise帽os if-else, switch-case-default. Sin embargo, existen plantillas generalizadas KeyToValueConverter y SwitchConverterque le permiten evitar agregar clases del mismo tipo en estructura al proyecto declarando valores booleanos y ramas directamente en el marcado.
Concepto
<KeyToValueConverter
Key="KeyForMatching"
Value="ValueIfKeyMatched"
ByDefault="ValueIfKeyNotMatched" />
<SwitchConverter
ByDefault="ValueZ">
<Case
Key="KeyA"
Value="ValueA" />
<Case
Key="KeyB"
Value="ValueB" />
<Case
Key="KeyC"
Value="ValueC" />
</SwitchConverter>Solicitud
<KeyToValueConverter
x:Key="TrueToVisibleConverter"
Key="True"
Value="Visible"
ByDefault="Collapsed" />
<ProgressBar
Visibility="{Binding IsBusy, Converter={StaticResource TrueToVisibleConverter}}" /><SwitchConverter
x:Key="CodeToBackgroundConverter"
ByDefault="White">
<Case
Key="R"
Value="Red" />
<Case
Key="G"
Value="Green" />
<Case
Key="B"
Value="Blue" />
</SwitchConverter>
<Control
Background="{Binding Code, Converter={StaticResource CodeToBackgroundConverter}}" />KeyToValueConverter - Key, , Value, ByDefault.
SwitchConverter - Case Key, Case , 篓C31C, 篓C90C篓C32C, .
Value ByDefault , , .
KeyToValueConverter ConverterParameter KeySource
<KeyToValueConverter
x:Key="EqualsToHiddenConverter"
KeySource="ConverterParameter"
Value="Collapsed"
ByDefault="Visible" />
<Control
Visiblity="{Binding Items.Count, ConverterParameter=0, Converter={StaticResource EqualsToHiddenConverter}}" />
<TextBlock
Visiblity="{Binding Text, ConverterParameter='Hide Me', Converter={StaticResource EqualsToHiddenConverter}}" /> KeySource :
Manual (by default) - Key ,
ConverterParameter - ConverterParameter ,
PreferManual - manual Key , ConverterParameter
PreferConverterParameter - ConverterParameter , manual Key
, SwitchConverter Case TypedCase,
<SwitchConverter
ByDefault="Undefined value">
<TypedCase
Key="system:String"
Value="String value" />
<Case
Key="0"
Value="Zero" />
<Case
Key="1"
Value="One" />
<TypedCase
Key="system:Int32"
Value="Int32 value" />
</SwitchConverter> . SwitchConverter DiagnosticKey, , Trace
var diagnosticMessage = matchedCase.Is()
? $"{DiagnosticKey}: '{matchedValue}' matched by key '{matchedCase.Key}' for '{value}' and converted to '{convertedValue}'"
: $"{DiagnosticKey}: The default value '{matchedValue}' matched for '{value}' and converted to '{convertedValue}'";
Trace.WriteLine(diagnosticMessage);<SwitchConverter
DiagnosticKey="UniqDiagnosticKey"
x:Key="CodeToBackgroundConverter"
ByDefault="White">
...
</SwitchConverter>Dependency Value Converter
Key, Value ByDefault (Dependency Properties), Cases DependencyObject. , , Binding,
<KeyToValueConverter
Key="AnyKey"
Value="{Binding MatchedValue, Source={StaticResource AnyResource}}"
ByDefault="{Binding DefaultValue, Source={StaticResource AnyResource}}" />
<KeyToValueConverter
Key="AnyKey"
Value="{Localizing MatchedTitle}"
ByDefault="{Localizing DefaultTitle}" />Inline Converter
, IValueConverter, code-behind .
, .
, code-behind Converting ConvertingBack
<Grid>
<Grid.Resources>
<InlineConverter
x:Key="ComplexInlineConverter"
Converting="InlineConverter_OnConverting"
ConvertingBack="InlineConverter_OnConverting" />
</Grid.Resources>
<TextBlock
Text="{Binding Number, Converter={StaticResource InlineConverter}}"/>
</Grid>private void InlineConverter_OnConverting(object sender, ConverterEventArgs e)
{
// e.Value - access to input value
// this.DataContext - access to Data Context or another properties of the view
// access to child visual elements of this root view
e.ConvertedValue = // set output value
$"DataContext: {DataContext}, Converter Value: {e.Value}";
}
private void InlineConverter_OnConvertingBack(object sender, ConverterEventArgs e)
{
// ...
}Aggregate Converter
, .
<AggregateConverter>
<StepAConverter />
<StepBConverter />
<StepCConverter />
</AggregateConverter>App.xaml
Es 煤til colocar convertidores de valor gen茅rico en un diccionario de recursos separado y luego combinarlos como recursos globales en el archivo App.xaml. Esto le permite reutilizar convertidores de valor en diferentes representaciones sin volver a declararlos.
<Application
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="Any.App">
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary
Source="AppConverters.xaml" />
...
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
</Application>Marco Ace
Se pueden encontrar ejemplos de implementaci贸n de los convertidores presentados en la biblioteca Ace Framework bitbucket de gitlab
隆Con gratitud por su atenci贸n e inter茅s!