如何在XAML(x:Bind)中将Double转换为Thickness?

tcbh2hod  于 2022-12-25  发布在  其他
关注(0)|答案(1)|浏览(128)

我试图将一个滑块控件的值传递给另一个控件的边框粗细:

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

但出现以下错误:
无法将类型“System.Double”直接绑定到“Microsoft.UI.Xaml.Thickness”。请使用类型转换、转换器或函数绑定来更改该类型
这种转换是如何完成的?

owfi6suc

owfi6suc1#

您可以像这样创建转换器:

    • 双倍厚度转换器. 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();
    }
}

并像这样使用它:

    • 主页. 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>
    • 更新**

添加任意系数作为转换器参数。现在你可以设置一个系数为左,上,右和底部厚度。例如,你可以设置'0,0,0,1'如果你只想使用底部厚度或设置'1,2,1,2'加倍顶部和底部的厚度。

相关问题