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

Fem*_*jin 10 c# xamarin.forms

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

我用来设置Image的代码:

            ImageSource iconsource =ImageSource.FromStream(() => new MemoryStream(ImgASBytes));
            Button Icon = new Button ();
            Icon.Image = iconsource ;
Run Code Online (Sandbox Code Playgroud)

我遇到的错误:

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

Ste*_*oix 13

ImageSource.FromStream ()返回一个StreamImageSource(参见文档).Button.Image仅接受FileImageSource(参见文档).

这意味着无论你多么努力地将一个人投入另一个人,你想要实现的目标都无法发挥作用.

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

Icon.Image = ImageSource.FromFile ("foobar.png");
Run Code Online (Sandbox Code Playgroud)

要么

Icon.Image = "foobar.png";
Run Code Online (Sandbox Code Playgroud)

  • ImageSource.FromFile还返回ImageSource实例.所以Icon.Image = ImageSource.FromFile("foobar.png"); 也会导致类型错误.Icon.Image =''foobar.png"有效 (3认同)

Vic*_*aru 6

接受的答案是真实的,你不能 StreamImageSourceFileImageSource,我认为真正的问题是如何在PCL共享图像,并利用它们上的一个按钮,就像一个会创建时Image控制形式.

答案是让a Grid包含一个Button和一个Image对象,其中Image重叠的是Button.

例如,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);
Run Code Online (Sandbox Code Playgroud)

您可能需要使用尺寸和厚度值,但这应该是一个带图标的可点击按钮.