Home > Software design >  How to convert Double to Thickness in XAML (x:Bind)?
How to convert Double to Thickness in XAML (x:Bind)?

Time:12-24

I'm trying to pass the value of a slider control to the border thickness of another control:

<Border 
   BorderThickness="{x:Bind ThicknessSlider.Value, Mode=OneWay}">
</Border>

But this error occurs:

Cannot directly bind type 'System.Double' to 'Microsoft.UI.Xaml.Thickness'. Use a cast, converter or function binding to change the type

How is this conversion done?

CodePudding user response:

You can create a converter like this:

DoubleToThicknessConverter.cs

using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Data;
using System;

namespace Converters;

public class DoubleToThicknessConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        if (value is double doubleValue)
        {
            List<int>? coefficients = (parameter as string)?
                .Split(',')
                .Select(x => int.Parse(x))
                .ToList<int>();

            if (coefficients?.Count is not 4)
            {
                coefficients = new() { 1, 1, 1, 1 };
            }

            return new Thickness(
                left: doubleValue * coefficients[0],
                top: doubleValue * coefficients[1],
                right: doubleValue * coefficients[2],
                bottom: doubleValue * coefficients[3]);
        }

        throw new ArgumentException();
    }

    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        throw new NotImplementedException();
    }
}

And use it like this:

MainPage.xaml

<Page
    x:Class="Converters.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:local="using:Converters"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"
    mc:Ignorable="d">
    
    <Page.Resources>
        <local:DoubleToThicknessConverter x:Key="DoubleToThicknessConverter" />
    </Page.Resources>

    <Border
        BorderBrush="SkyBlue"
        BorderThickness="{x:Bind ThicknessSlider.Value, Mode=OneWay, Converter={StaticResource DoubleToThicknessConverter}, ConverterParameter='0,3,1,3'}">
        <Slider x:Name="ThicknessSlider" />
    </Border>
    
</Page>

UPDATE

Added arbitrary coefficients as converter parameter. Now you can set a coefficient to left, top, right and bottom thickness. For example, you can set '0,0,0,1' if you only want to use the bottom thickness or set '1,2,1,2' to double the thickness of top and bottom.

  • Related