执行此操作的正确方法在 Charles Petzold 关于 Xamarin Forms 的优秀书籍的第 13 章中进行了描述:https ://developer.xamarin.com/guides/xamarin-forms/creating-mobile-apps-xamarin-forms/
我解决这个问题的方法是(与书不同)为图像文件路径使用转换器。Button.Image 属性是一个 FileImageSource 对象,它需要一个文件路径。不幸的是,您不能在 PCL 中使用嵌入式资源或内容文件。您必须在每个 iOS、Android 和 UWP 项目中添加单独的图像文件。我这样做的方法是将图像添加到 PCL 并使用链接(添加现有文件对话框上的选项)。
所以这是我对上述问题的转换器方法
<Button Image="{Binding Converter={StaticResource FileImageSourceConverter}, ConverterParameter=someImage.png}" />
静态资源...
<ContentPage.Resources>
<ResourceDictionary>
<local:FileImageSourceConverter x:Key="FileImageSourceConverter"/>
</ResourceDictionary>
</ContentPage.Resources>
转换器...
public class FileImageSourceConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
string filename = parameter as string;
switch(Device.RuntimePlatform)
{
case Device.iOS:
case Device.Android:
default:
return filename;
case Device.Windows:
return Path.Combine("Images", filename);
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
这种方法的优点是 (1) 您的 XAML 不会被 OnPlatform 元素弄得一团糟;(2)你不需要把你的图片放在UWP项目的根目录下;(3) 比使用自定义渲染解决一些人建议的相同问题要简单得多。