在 Xamarin Forms 中,我试图创建一个带有属性的 xaml 转换器。
这将用于,例如,基于隐藏属性的代码以不同方式显示列表中的值。
我的代码基于此:https://stackoverflow.com/a/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 绑定(bind)到 PropParam。
但如果我使用:
<conv:MyConverter x:Key="cnv" ConvParam="{Binding Source={Reference MainPageXaml}, Path=PropParam}" />
错误 位置 10:39。未找到“ConvParam”的属性、可绑定(bind)属性或事件,或者值和属性之间的类型不匹配 显示并且应用程序无法编译。
楼盘转换参数 本身在 xaml 中被识别:如果我将上面的行替换为
<conv:MyConverter x:Key="cnv" ConvParam="333" />
一切正常。
我使用的绑定(bind)表达式 ({Binding Source={Reference MainPageXaml}, Path=PropParam}) 实际上有效,如果用作标签的文本属性的源:
<Label Text="{Binding Source={Reference MainPageXaml}, Path=PropParam}" />
但是如果我在资源中使用它,它就不起作用。
最佳答案
感谢 朱丽潘 我可以让它工作!
正如他所指出的,ConvParam 必须是 BindableProperty,所以我修改了我的转换器以从 BindableObject 继承并将 ConvParam 定义为 BindableProperty。
转换器:
namespace App2.Converters
{
class MyConverter : BindableObject, IValueConverter
{
public static readonly BindableProperty ConvParamProperty = BindableProperty.Create(nameof(ConvParam), typeof(int), typeof(MyConverter));
public int ConvParam
{
get { return (int)GetValue(ConvParamProperty); }
set { SetValue(ConvParamProperty, value); }
}
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();
}
}
}
关于c# - Xamarin 形成 Xaml 转换器 : Bindable property,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58181277/