User Tools

Site Tools


notes:uwp:converters

Converters in XAML

Converters implement the IValueConverter interface that defines two methods:

  • Convert - called before the data from the source is passed to the target for displaying it in UI.
  • ConvertBack - called before the data from the UI is passed to the source for storage or updates. This method is called only in TwoWay data bindings.

In other words:

  • When data is passed from the source, the binding engine calls Convert and passes the returned data to the target.
  • When data is passed from the target, the binding engine calls ConvertBack and passes the returned data to the source.

Declaration

Declare a converter:

xmlns:common="using:WBS.MyApp.Common"
...
<common:BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/>

Error handling

If there is an error in the conversion, do not throw an exception. Instead, return DependencyProperty.UnsetValue, which will stop the data transfer.

MSDN: DependencyProperty.UnsetValue specifies a static value that is used by the property system rather than null to indicate that the property exists, but does not have its value set.

Converters and MVVM

  • Converters belong to the Views.
  • Converters can be a source of performance problems in the Views if there are lots of items - each item executes a converter.

Avoid using converters with the items of ListControls. Put conversions as an additional property in ViewModel instead.

Examples

Example: BooleanToGridLengthConverter

public sealed class BooleanToGridLengthConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        GridLength lenZero = new GridLength(0, GridUnitType.Pixel);
        GridLength lenAuto = GridLength.Auto;
 
        return ((value is bool && (bool)value) ? lenAuto : lenZero);
    }
 
    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        throw new NotImplementedException();
    }
}
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition />
        <ColumnDefinition Width="{Binding  ElementName=CheckBox1, Path=IsChecked, 
                                           Converter={StaticResource BooleanToGridLengthConverter}}" />
    </Grid.ColumnDefinitions>
</Grid>

Example: DoubleToTimeSpanConverter

class DoubleToTimeSpanConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        double hours = (double)value;
        TimeSpan span = TimeSpan.FromHours(hours);
        return span;
    }
 
    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        TimeSpan span = (TimeSpan)value;
        double hours = span.TotalHours;
        return hours;
    }
}

Example: NumberToBooleanConverter

class NumberToBooleanConverter : IValueConverter
{
    // Returns True is the provided number is greater than 0.
    // The value parameter may be double, float, int, or decimal.
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        if (value == null)
            return false;
        string str = value.ToString();
 
        double n;
        if (!(Double.TryParse(str, out n)))
            return false;
 
        return (n > 0.000001);
    }
 
    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        throw new NotImplementedException();
    }
}
notes/uwp/converters.txt · Last modified: 2017/03/10 by admin