我尝试使用示例代码跟踪@CraigDunn的下面的例子
someButton.Image = ImageSource.FromFile("imageName.png");我自己的尝试是这样的:
_NavBarPrevPage = new Button
{
Image = ImageSource.FromResource("media_step_back.png")),
BackgroundColor = Color.Red,
TextColor = Color.White,
};对我来说,IDE告诉我:
The type Xamarin.Forms.ImageSource can't be converted to Xamarin.Forms.FileImageSource. An explicit conversion exists. Perhaps a conversion is missing.我想我正在做@CraigDunn提议的事情。我做错了什么?
我尝试了以下方法,并且能够消除当前答案中的转换错误,但是该图像没有显示在按钮上,而是显示在图像中,因此文件名是正确的:
var nImg = new FileImageSource()
{
File = "media_step_back.png",
};
_NavBarPrevPage = new Button
{
Image =nImg,
};发布于 2017-11-29 17:30:23
如果您需要的是一个带有图像的按钮,该按钮是通过代码隐藏实现的:
Button button = new Button
{
BackgroundColor = Color.Red,
Font = Font.Default,
FontSize = 10,
TextColor = Color.White,
HeightRequest = 35,
WidthRequest = 80
};
button.Image = "media_step_back.png";
this.Content = button;请记住将图像文件(media_step_back.png)放在目标平台的资源文件夹中
更新:
您的问题是没有在属性文件夹和目标平台的资源文件夹中添加图像源(请注意,在下面的示例中,我在每个xamarin.png“属性”文件夹、Android的“资源”和iOS的“资源”文件夹中添加了一个图像)。
下面是我将按钮放置到StackLayout中的更新代码(如果没有StackLayout,它也可以工作):
public class MainPageNew : ContentPage
{
public MainPageNew()
{
StackLayout parent = new StackLayout();
Button button = new Button
{
BackgroundColor = Color.Red,
Font = Font.Default,
FontSize = 10,
TextColor = Color.White,
HeightRequest = 300,
WidthRequest = 80
};
//button.Image = "media_step_back.png";
button.Image = "xamarin.png";
parent.Children.Add(button);
this.Content = parent;
}安卓

iOS:

这是更新代码的下载链接。
https://stackoverflow.com/questions/47556967
复制相似问题