Xamarin Forms:可绑定 属性 的 IMarkupExtension 不起作用
Xamarin Forms: IMarkupExtension with bindable property does not work
绑定不适用于图像标记。
当我调试时,我看到Extension class 中的Source 的值总是为null?
但是标签内容不为空
Xaml
<Label Text="{Binding Image}" />
<Image Source="{classes:ImageResource Source={Binding Image}}" />
ImageResourceExtension
// You exclude the 'Extension' suffix when using in Xaml markup
[Preserve(AllMembers = true)]
[ContentProperty("Source")]
public class ImageResourceExtension : BindableObject, IMarkupExtension
{
public static readonly BindableProperty SourceProperty = BindableProperty.Create(nameof(Source), typeof(string), typeof(string), null);
public string Source
{
get { return (string)GetValue(SourceProperty); }
set { SetValue(SourceProperty, value); }
}
public object ProvideValue(IServiceProvider serviceProvider)
{
if (Source == null)
return null;
// Do your translation lookup here, using whatever method you require
var imageSource = ImageSource.FromResource(Source);
return imageSource;
}
}
当然不是!
并不是因为您从 BindableObject
继承,所以您的对象神奇地具有 BindingContext
集。如果没有 BindingContext
,就无法解析 {Binding Image}
.
您要找的是转换器
class ImageSourceConverter : IValueConverter
{
public object ConvertTo (object value, ...)
{
return ImageSource.FromResource(Source);
}
public object ConvertFrom (object value, ...)
{
throw new NotImplementedException ();
}
}
然后将此转换器添加到您的 Xaml 根元素资源(或 Application.Resources 并在您的绑定中使用它
<Label Text="{Binding Image}" />
<Image Source="{Binding Image, Converter={StaticResource myConverter}}" />
绑定不适用于图像标记。 当我调试时,我看到Extension class 中的Source 的值总是为null? 但是标签内容不为空
Xaml
<Label Text="{Binding Image}" />
<Image Source="{classes:ImageResource Source={Binding Image}}" />
ImageResourceExtension
// You exclude the 'Extension' suffix when using in Xaml markup
[Preserve(AllMembers = true)]
[ContentProperty("Source")]
public class ImageResourceExtension : BindableObject, IMarkupExtension
{
public static readonly BindableProperty SourceProperty = BindableProperty.Create(nameof(Source), typeof(string), typeof(string), null);
public string Source
{
get { return (string)GetValue(SourceProperty); }
set { SetValue(SourceProperty, value); }
}
public object ProvideValue(IServiceProvider serviceProvider)
{
if (Source == null)
return null;
// Do your translation lookup here, using whatever method you require
var imageSource = ImageSource.FromResource(Source);
return imageSource;
}
}
当然不是!
并不是因为您从 BindableObject
继承,所以您的对象神奇地具有 BindingContext
集。如果没有 BindingContext
,就无法解析 {Binding Image}
.
您要找的是转换器
class ImageSourceConverter : IValueConverter
{
public object ConvertTo (object value, ...)
{
return ImageSource.FromResource(Source);
}
public object ConvertFrom (object value, ...)
{
throw new NotImplementedException ();
}
}
然后将此转换器添加到您的 Xaml 根元素资源(或 Application.Resources 并在您的绑定中使用它
<Label Text="{Binding Image}" />
<Image Source="{Binding Image, Converter={StaticResource myConverter}}" />