我正在尝试使用Xamarin Forms创建带有属性的xaml转换器。
例如,基于代码后面的属性,以不同的方式显示列表中的值。
我根据这个代码进行了编写:https://dev59.com/GF0a5IYBdhLWcg3w48Tn#29869734。
转换器:
namespace App2.Converters
{
class MyConverter : IValueConverter
{
public int ConvParam { get; set; }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return $"value: {value} - ConvParam: {ConvParam}";
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
XAML:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:conv="clr-namespace:App2.Converters"
x:Class="App2.MainPage"
x:Name="MainPageXaml">
<ContentPage.Resources>
<conv:MyConverter x:Key="cnv" ConvParam="{Binding Source={Reference MainPageXaml}, Path=PropParam}" />
<!--<conv:MyConverter x:Key="cnv" ConvParam="333" />-->
</ContentPage.Resources>
<StackLayout Orientation="Vertical">
<!-- Place new controls here -->
<Label Text="{Binding Source={Reference MainPageXaml}, Path=PropVal}" />
<Label Text="{Binding Source={Reference MainPageXaml}, Path=PropParam}" />
<Label Text="{Binding Source={Reference MainPageXaml}, Path=PropVal, Converter={StaticResource cnv}}" />
</StackLayout>
代码后台:
public partial class MainPage : ContentPage
{
public int PropVal { get; set; } = 111;
public int PropParam { get; set; } = 222;
public MainPage()
{
InitializeComponent();
}
}
目标是将我的转换器的ConvParam绑定到代码后台的PropParam。
但如果我使用:
<conv:MyConverter x:Key="cnv" ConvParam="{Binding Source={Reference MainPageXaml}, Path=PropParam}" />
显示错误:位置10:39。未找到“ConvParam”的属性、绑定属性或事件,或值与属性之间类型不匹配,导致应用程序无法编译。
xaml中已经识别了属性ConvParam本身:如果我使用以下行替换上述行:
<conv:MyConverter x:Key="cnv" ConvParam="333" />
一切正常。
我使用的绑定表达式 ({Binding Source={Reference MainPageXaml}, Path=PropParam}) 实际上是有效的,如果用作标签的文本属性的源:
<Label Text="{Binding Source={Reference MainPageXaml}, Path=PropParam}" />
但如果我在资源中使用它,它就不起作用。