如何将ImageSource设置为Xamarin.Forms.Button?

我正在尝试使用按钮中的图像属性添加背景图像。 我面临的问题是我无法将StreamImageSource设置为按钮背景。 如果我尝试这样做,我会遇到下面给出的错误。

我用来设置Image的代码:

ImageSource iconsource =ImageSource.FromStream(() => new MemoryStream(ImgASBytes)); Button Icon = new Button (); Icon.Image = iconsource ; 

我遇到的错误:

错误CS0266:无法将类型’Xamarin.Forms.ImageSource’隐式转换为’Xamarin.Forms.FileImageSource’。 存在显式转换(您是否错过了演员?)

ImageSource.FromStream ()返回一个StreamImageSource (参见docs )。 Button.Image只接受FileImageSource (参见docs )。

这意味着无论你多么努力地将一个人投入另一个人,你想要实现的目标都行不通。

Button.Image将接受存储为平台项目中资源的图像,并加载:

 Icon.Image = ImageSource.FromFile ("foobar.png"); 

要么

 Icon.Image = "foobar.png"; 

接受的答案是真的,你不能 StreamImageSourceFileImageSource ,我认为真正的问题是如何在PCL中共享图像并在按钮上使用它们,就像创建Image窗体控件时一样。

答案是让Grid包含一个Button和一个Image对象,其中ImageButton重叠。

例如,C#代码可能如下所示:

 ImageSource imageSource = ImageSource.FromStream(() => new MemoryStream(imageAsBytes)); Button iconButton = new Button (); iconButton.VerticalOptions = LayoutOptions.FillAndExpand; iconButton.HorizontalOptions = LayoutOptions.FillAndExpand; var image = new Image(); image.Source = imageSource; // So it doesn't eat up clicks that should go to the button: image.InputTransparent = true; // Give it a margin so it doesn't extend to the edge of the grid image.Margin = new Thickness(10); var grid = new Grid(); // If we don't set a width request, it may stretch horizontally in a stack grid.WidthRequest = 48; // Add the button first, so it is under the image... grid.Children.Add(iconButton); // ...then add the image grid.Children.Add(image); 

您可能需要使用尺寸和厚度值,但这应该会为您提供带有图标的可点击按钮。

对于任何可能感到困惑的人,截至2014年1月30日

使用“ Image视图时,可以将源设置为共享项目或PCL中的图像。 这也在Xamarin的文档中显示: 这里

使用button ,您无法使用存储在共享项目或PCL中的源图像,甚至不会浪费您的时间,因为button类的Image属性需要在访问PCL中的图像时不兼容的FileImageSource或共享项目。 但是,您可以使用本机项目中加载的图像,这就是为什么您会看到上面的某些人说他们有解决方案

小心文件名中的大写和小写。

我想知道为什么我的按钮图像在模拟器上正确显示,但在我的iPhone上却没有。

在设备上,文件名必须完全匹配,模拟器不关心文件名中的大写和小写。

我使用它,它的工作原理

 var imageA = new Image(); imageA.Source=(FileImageSource)ImageSource.FromFile(allergeneLocation)}; 

要么

 var imageA = new Image() { BackgroundColor = Color.Teal, Source = (FileImageSource)ImageSource.FromFile(allergeneLocation)}, }; 

这是我尝试过的:

 Button refreshBut = new Button { Image = (FileImageSource) (ImageSource.FromFile("refreshBut.png")) }; 

当它编译我然后获得一个未处理的空引用exception与描述:对象引用未设置为对象的实例。 我不确定这是否会帮助其他人试图解决这个问题,但我在同一堵墙上。