Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 42 ยท Controls and Binding

Binding Modes and Value Converters

Learn the .NET MAUI binding modes (OneWay, TwoWay, OneTime, OneWayToSource), StringFormat, IValueConverter, IMultiValueConverter and UpdateSourceEventName, with runnable converter stand-ins.

Once a value flows from a view model to the screen, two questions come up quickly. Which way should data travel: does typing in an Entry change the view model too? And what if the source value is not what you want to show: a bool that should become a colour, a DateTime that should read "3 days ago"? Binding modes answer the first question, string formats and value converters the second.

The XAML in this lesson is read-only because MAUI cannot run on this site. The converters are ordinary C# classes though, so the logic is shown with labelled stand-ins that use a small copy of the IValueConverter shape (MAUI's own interface needs the MAUI assemblies).

Binding modes

BindingMode controls the direction of the data flow:

Mode Direction Typical use
OneWay source to target labels, images, read-only displays
TwoWay both ways Entry.Text, Switch.IsToggled, Slider.Value
OneWayToSource target to source rare: push a control's value into the model
OneTime source to target, once static data that never changes (fastest)
Default depends on the property what you get if you write nothing

Every bindable property has a default mode chosen by its author. Label.Text defaults to OneWay, Entry.Text, Editor.Text, Switch.IsToggled, Slider.Value, DatePicker.Date and Picker.SelectedItem default to TwoWay. So the usual form field needs no mode at all:

XML
<Entry Text="{Binding Email}" />                          <!-- TwoWay by default -->
<Label Text="{Binding Email}" />                          <!-- OneWay by default -->
<Label Text="{Binding AppVersion, Mode=OneTime}" />       <!-- read once -->

Setting the mode explicitly is good documentation when the direction matters, and necessary when you want to change a default, for example a read-only display of a slider value that must not write back.

When does a two-way binding write back?

For Entry.Text the source is updated on every keystroke by default. That is great for live validation but wasteful if the setter does something heavy such as filtering a big list. You can delay the write with UpdateSourceEventName, which names the event on the target that triggers the update:

XML
<!-- Write to the source only when the user finishes (presses Return or leaves) -->
<Entry Text="{Binding Query, UpdateSourceEventName=Completed}" />

Another approach is to bind to a property that debounces: it stores the text at once but waits 300 ms before running the search.

StringFormat

StringFormat is the easiest way to shape text, and it uses the same format strings as string.Format. The format must go in quotes when it has braces, because { normally starts a markup extension:

XML
<Label Text="{Binding Price, StringFormat='Total: {0:C2}'}" />
<Label Text="{Binding Created, StringFormat='{0:dd MMM yyyy}'}" />
<Label Text="{Binding Progress, StringFormat='{0:P0} done'}" />

StringFormat works only on properties of type string (it is a text formatter). It is lost if you also add a converter that returns a non-string, so if both are needed, let the converter return the final text.

IValueConverter

When formatting is not enough, write a converter. A converter implements IValueConverter with two methods: Convert (source to target) and ConvertBack (target to source, used by two-way bindings):

C#
using System.Globalization;

public class BoolToColorConverter : IValueConverter
{
    public Color TrueColor { get; set; } = Colors.Green;
    public Color FalseColor { get; set; } = Colors.Red;

    public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture) =>
        value is true ? TrueColor : FalseColor;

    public object? ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) =>
        throw new NotSupportedException();      // one-way only
}

You declare it as a resource and refer to it with StaticResource:

XML
<ContentPage.Resources>
    <local:BoolToColorConverter x:Key="OnlineColor"
                                TrueColor="SeaGreen" FalseColor="Gray" />
</ContentPage.Resources>

<Label Text="Status" TextColor="{Binding IsOnline, Converter={StaticResource OnlineColor}}" />

The parameter argument comes from ConverterParameter, which lets one converter serve several bindings:

XML
<Label IsVisible="{Binding Count, Converter={StaticResource GreaterThan}, ConverterParameter=0}" />

Writing a converter you can test

The conversion logic is plain C#, so it belongs in code you can run and test. The stand-in below copies the interface shape and runs two converters: a "time ago" text converter and an "inverse bool" converter with a two-way round trip.

C# Stand-in: IValueConverter logic

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

A converter's Convert must be cheap and have no side effects: the framework may call it often. Return BindableProperty.UnsetValue (or the default) rather than throwing if the input is unexpected, because an exception in a binding can crash the page on some platforms.

Parameters, culture and null

Three details cause most converter bugs:

  1. value can be null while the page is loading, before the view model is ready. Always handle it.
  2. culture is the UI culture, not the current thread culture, in some paths; use it for number and date text so output matches the user's language.
  3. targetType tells you what the target property needs. A converter used for both string and Color targets can branch on it.

IMultiValueConverter and MultiBinding

When one target depends on several sources, use MultiBinding with an IMultiValueConverter. Its Convert receives an array of values:

XML
<Label>
    <Label.Text>
        <MultiBinding Converter="{StaticResource FullNameConverter}">
            <Binding Path="FirstName" />
            <Binding Path="LastName" />
        </MultiBinding>
    </Label.Text>
</Label>

For simple cases MultiBinding also accepts a StringFormat and needs no converter: StringFormat="{}{0} {1}" joins the two values with a space.

C# Stand-in: multi-value conversion

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Choosing between StringFormat, a converter and a view model property

  • Pure text shaping of one value: StringFormat.
  • Reusable, XAML-only conversion (bool to colour, enum to icon): a converter.
  • Logic that mixes several values or needs services: compute it in the view model and bind to the result.

The last choice is often the best in a large app because it is easier to test, a point the MVVM lesson returns to.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which mode does Entry.Text use when you do not set Mode?

    Properties that users edit, such as Entry.Text, default to TwoWay so typing updates the source.
  2. 2. What is the purpose of UpdateSourceEventName?

    It names the target event (for example Completed) after which a two-way binding writes the value to the source, instead of on every change.
  3. 3. Where is ConvertBack used?

    ConvertBack converts values flowing from the target to the source, so it matters only when the binding writes back.
  4. 4. Why should a converter handle null input?

    Bindings can evaluate before data is ready, so Convert may receive null; handling it prevents errors and blank crashes.

Summary

  • OneWay, TwoWay, OneTime and OneWayToSource set the direction; most controls pick a sensible default.
  • StringFormat shapes text, and UpdateSourceEventName delays write-back.
  • IValueConverter turns a source value into a target value (and back); declare it as a resource.
  • MultiBinding with IMultiValueConverter combines several sources; often a view model property is simpler.
  • Keep converter logic pure and null-safe so you can test it.

Next: CollectionView and Lists