绑定不适用于Image标记。 当我调试时,我看到Extension类中的Source值始终为null? 但标签的内容不是空的。
<Label Text="{Binding Image}" />
<Image Source="{classes:ImageResource Source={Binding Image}}" />
// 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;
}
}
答案 0 :(得分:7)
当然不是!
这不是因为你从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}}" />