我正在学习Xamarin数据绑定并学习以下代码:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:DataBinding"
x:Class="DataBinding.MainPage">
<StackLayout>
<Label x:Name="label" Text="twisting" FontSize="70" HorizontalOptions="Center" VerticalOptions="CenterAndExpand"
BindingContext="{x:Reference Name=slider}"
Rotation="{Binding Path=Value}">
</Label>
<Slider x:Name="slider" BackgroundColor="Yellow" Maximum="360" VerticalOptions="CenterAndExpand">
</Slider>
</StackLayout>
</ContentPage>
我想加倍扭转速度,所以我修改了代码:
<Label x:Name="label" Text="twisting" FontSize="70"
HorizontalOptions="Center" VerticalOptions="CenterAndExpand"
BindingContext="{x:Reference Name=slider}"
Rotation="{Binding Path=Value*2}">
</Label>
但是它根本不起作用。我知道以下解决方案有效,但是我想要一个与上述解决方案相关的解决方案:
<Slider x:Name="slider" BackgroundColor="Yellow" Maximum="720" VerticalOptions="CenterAndExpand">
</Slider>
如何做到?
UPDATE1
我将转换器自定义为以下代码:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using Xamarin.Forms;
namespace DataBinding
{
public class MyValueConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var speed = value as int?;
return speed * 2;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return null;
}
}
}
,然后如下修改xaml:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:DataBinding"
x:Class="DataBinding.MainPage">
<StackLayout>
<Label x:Name="label" Text="twisting" FontSize="70" HorizontalOptions="Center" VerticalOptions="CenterAndExpand"
BindingContext="{x:Reference Name=slider}"
Rotation="{Binding Path, Converter={StaticResource myCo
nverter}}">
</Label>
<Slider x:Name="slider" BackgroundColor="Yellow" Maximum="360" VerticalOptions="CenterAndExpand">
</Slider>
</StackLayout>
<ContentPage.Resources>
<ResourceDictionary>
<local:MyValueConverter x:Key="myConverter"></local:MyValueConverter>
</ResourceDictionary>
</ContentPage.Resources>
</ContentPage>
但是我的转换器无法正常工作,而且,我断点了,发现Convert
函数甚至没有被触发。
UPDATE2
我发现了原因,XAML中的标签应为以下内容:
<Label x:Name="label" Text="twisting" FontSize="70" HorizontalOptions="Center" VerticalOptions="CenterAndExpand"
BindingContext="{x:Reference Name=slider}"
Rotation="{Binding Path=Value, Converter={StaticResource myConverter}}">
</Label>
,并且Convert函数中的值类型为double而不是string:
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var tmp = (Double)value*2;
return tmp;
}
然后它起作用。