如何将双重转换为XAML(x:bind)中的厚度? 我试图将滑块控件的价值传递给另一个控制的边界厚度:

问题描述 投票:0回答:1
但是发生此错误:

cannot直接将类型的“ system.double”绑定到 'Microsoft.ui.xaml.thickness'。使用铸件,转换器或功能 绑定以更改类型

如何完成此转换?

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

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(); } }
c# xaml winui-3 winui windows-app-sdk
1个回答
2
投票
使用这样的使用:

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

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

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.