Pull to refresh

XAML Aesthetics: Value Converters

Programming *.NET *Industrial Programming *Xamarin *

This article presents generalized approaches for using value converters into writing of XAML code.

>> Read in Russian

IValueConverter Data Binding XAML WPF UWP Xamarin Forms UI SwitchConverter KeyToValueConverter InlineConverter AggregateConverter ResourceDictionary

Value converters together with a data binding mechanism are essential components into XAML-based development of user interfaces. Value converters imply the presence of logic placed in a separated class that implements the IValueConverter interface. Typically, the class name reflects the functional purpose, and the instances are declared in the markup.

Switch Converter & Key To Value Converter

At practice many value converters have trivial logic similar by structure with ternary operator (? :) or if-else, switch-case-default constructions. However, there are generalized patterns KeyToValueConverter and SwitchConverter, which allow to avoid adding to the project of similar by structure classes via declaring logical values and branches directly into markup.


	ByDefault="ValueIfKeyNotMatched" />

		Value="ValueA" />
		Value="ValueB" />
		Value="ValueC" />


	ByDefault="Collapsed" />
	Visibility="{Binding IsBusy, Converter={StaticResource TrueToVisibleConverter}}" />


		Value="Red" />
		Value="Green" />
		Value="Blue" />
	Background="{Binding Code, Converter={StaticResource CodeToBackgroundConverter}}" />

KeyToValueConverter - checks the input value for compliance with the value from the Key property, if the match is met, then the value from the Value property is taken as the output, otherwise from the ByDefault property.

SwitchConverter - searches for the first matching Case from the list by its key from the Key property, if the corresponding Case is found, then the value specified in it from the Value property is taken, otherwise from the ByDefault property, specified in the converter itself.

If the property Value orByDefault is not explicitly set, but the corresponding condition is satisfied, then in this case, an ordinary forwarding of the input value as an output occurs.

Also, it is sometimes useful for KeyToValueConverter to set a key in ConverterParameter via the KeySource property

	ByDefault="Visible" />
	Visiblity="{Binding Items.Count, ConverterParameter=0, Converter={StaticResource EqualsToHiddenConverter}}" />

	Visiblity="{Binding Text, ConverterParameter='Hide Me', Converter={StaticResource EqualsToHiddenConverter}}" />

There are four work modes of KeySource for special cases: 

Manual (by default) -  the value from the Key property is always used as a key during matching, or the value is forwarded when it is not set

ConverterParameter -  the value from the binding's property ConverterParameter is always used as the key during matching, or the value is passed through when it is not set

PreferManual - if manual Key is explicitly set, it takes precedence over ConverterParameter

PreferConverterParameter - if ConverterParameter is explicitly set, then it takes precedence over manual Key

Note that SwitchConverter, in addition to the usual Case, also has TypedCase, the main difference of which is matching by value type

	ByDefault="Undefined value">
		Value="String value" />
		Value="Zero" />
		Value="One" />
		Value="Int32 value" />

Sometimes it becomes necessary to debug the value converter. For this purpose, SwitchConverter has a DiagnosticKey property, if it is been set, then when the data binding is been triggered, diagnostic messages of the following format will be displayed in 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}'";


Dependency Value Converter

It is also useful to declare Key, Value and ByDefault properties as Dependency Properties, that means inheritance of converters and Cases from the DependencyObject class. Although value converters are usually not elements of the visual tree, which partly limits the work of the data binding mechanism, nevertheless, it remains possible to bind to static resources or descendants of the Binding class, for example

	Value="{Binding MatchedValue, Source={StaticResource AnyResource}}"
	ByDefault="{Binding DefaultValue, Source={StaticResource AnyResource}}" />
	Value="{Localizing MatchedTitle}"
	ByDefault="{Localizing DefaultTitle}" />

Inline Converter

Inline Converter allow to transfer the values conversion logic ​​from a separate class that implements the IValueConverter interface into the code-behind class of a concrete view based on the event model.

This allows to access the view and its individual visual elements from the conversion logic during implementation of complex scenarios that are difficult to implement with the classical approach.

To do this, you need to add the converter declaration to the markup, and into the code-behind class define handlers for the corresponding Converting and ConvertingBack events

			ConvertingBack="InlineConverter_OnConverting" />
		Text="{Binding Number, Converter={StaticResource InlineConverter}}" />
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

Aggregate converter intends for combining converters into chains, while the value is converted sequentially in the order in which nested converters are declared.

	<StepAConverter />
	<StepBConverter />
	<StepCConverter />


It is useful to locate generic value converters in a separate Resource Dictionary and then merge them as global resources into the App.xaml file. This allows to reuse value converters in different views without re-declaring them.

					Source="AppConverters.xaml" />

Ace Framework

Examples of implementation of the presented converters can be found into the Ace Framework library gitlab bitbucket

With gratitude for your attention and interest!

Rating 0
Views 1.2K
Comments 0
Comments Leave a comment