我有一些xaml标记来根据绑定指定图像文件。
<Image Grid.Row="0" Grid.Column="3" Source="{Binding ImageSource}" VerticalOptions="Center"/>
我的模型类使用此命令返回文件名:
public string ImageSource {
get {
return (PaymentType == PaymentType.Check ? "check" : "card");
}
}
这适用于iOS,因为这些文件名为check.png,check @ 2x.png等,我的图片正在显示。但是Android上没有显示图片,因为我需要指定&#34; check.png&#34;或&#34; card.png&#34;。如何在保持严格的模型类的同时为Android工作呢?
答案 0 :(得分:3)
这可以使用Value Converter实现:
namespace MyApp.ValueConverters
{
using System;
using System.Globalization;
using Xamarin.Forms;
public class ImageSourceConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is string)
{
switch (Device.OS)
{
case TargetPlatform.Android:
return string.Format("{0}.png", value);
default:
// No conversion for other platforms
}
}
return value;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
然后设置任何所需的页面以访问新的ImageSourceConverter:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:converters="clr-namespace:MyApp.ValueConverters;assembly=MyApp"
...>
将转换器指定为页面资源,以便可以在绑定中使用:
<ContentPage.Resources>
<ResourceDictionary>
...
<converters:ImageSourceConverter x:Key="MyImageSourceConverter" />
</ResourceDictionary>
</ContentPage.Resources>
最后,更新任何图像源绑定以使用转换器:
<Image Grid.Row="0" Grid.Column="3" VerticalOptions="Center"
Source="{Binding ImageSource, Converter={StaticResource MyImageSourceConverter}}" />
答案 1 :(得分:1)
查看文档here。
最简单的方法是使用这样的编译器指令:
public string ImageSource {
get {
#if __IOS__
return (PaymentType == PaymentType.Check ? "check" : "card");
#endif
#if __ANDROID__
return (PaymentType == PaymentType.Check ? "check.png" : "card.png");
#endif
}
}
但可能有更优雅的解决方案。