简体   繁体   English

图像未显示(Xamarin 表单)

[英]Image is not displaying (Xamarin Forms)

I have shown the data on screen except image now i also want to see image as i can see all the data like id name etc, below are the codes: What changes do i need to make and where?我已经在屏幕上显示了除图像以外的数据,现在我还想查看图像,因为我可以看到所有数据,例如 ID 名称等,以下是代码: 我需要进行哪些更改以及在哪里进行?

Page 1 XAML C sharp code: (Changes on this page?)第 1 页 XAML C 清晰代码:(此页面上的更改?)

 public partial class MainPage : ContentPage
    {
        private static readonly HttpClient client = new HttpClient();
        public UserResponse result;
        public String test;
        public MyUser user;
        public MainPage()
        {
            InitializeComponent();
            //     Task.Run(async () => await GetinfoAsync());  
            _ = GetinfoAsync();
        }
        public async Task GetinfoAsync()
        {
            var responseString = await client.GetStringAsync("https://reqres.in/api/users/2");

            result = JsonConvert.DeserializeObject<UserResponse>(responseString); 

            if (result != null)
            {
                Device.BeginInvokeOnMainThread(() =>
                {
                    test = dis.Text = "Id:- " + result.Data.id + "\nEmail:- " + result.Data.email + "\nFirst Name:- " + result.Data.first_name + "\nLast Name:- " + result.Data.last_name + "\nImage:- " + result.Data.avatar; dis.Text = test;
                });
            }
        }

        private async void click_me(Object sender, EventArgs args)
        {
            await this.Navigation.PushAsync(new Data(result));
        }

Page 2 XAML C sharp Code: (Changes on this page?)第 2 页 XAML C 清晰代码:(此页面上的更改?)

public partial class Data : ContentPage
    {

        private MyUser _obj;
        public MyUser obj
        {
            get { return _obj; }
            set
            {
                _obj = value;
                OnPropertyChanged();
            }
        }

        public String show;

        public Data(UserResponse result)
        {
            //show = test;
            InitializeComponent();
            obj = result.Data;
            // displaylabel.Text = test;

        }

Page 2 XAML code for design:第 2 页 XAML 代码设计:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             mc:Ignorable="d"
             x:Class="demo.Data" x:Name="MyPage" >
    <ContentPage.Content >

        <StackLayout Padding="20">
            <Label Text="Id" TextColor="Red" />
            <Editor BindingContext="{x:Reference Name=MyPage}" Text="{Binding obj.id}"   IsReadOnly="True" />
            <Label Text="First Name" TextColor="Red"/>
            <Editor BindingContext="{x:Reference Name=MyPage}" Text="{Binding obj.first_name}" IsReadOnly="True"/>
            <Label Text="Last Name" TextColor="Red"/>
            <Editor BindingContext="{x:Reference Name=MyPage}" Text="{Binding obj.last_name}" IsReadOnly="True"/>
            <Label Text="Email" TextColor="Red"/>
            <Editor BindingContext="{x:Reference Name=MyPage}" Text="{Binding obj.email}" IsReadOnly="True"/>
            <Editor BindingContext="{x:Reference Name=MyPage}" Text="Image" IsReadOnly="True"/>
            <Image BindingContext="{x:Reference Name=MyPage}" Source="{Binding obj.avatar}"/>



        </StackLayout>

    </ContentPage.Content>

</ContentPage>

这就是我得到的

Since the value of obj.avatar is of type string and Source of ImageSource has to be of type ImageSource .由于值obj.avatar是字符串类型和SourceImageSource必须是类型ImageSource Use converter for this.为此使用转换器。

Converter code转换器代码

Add it in the same namespace as your Data class.将它添加到与 Data 类相同的命名空间中。


namespace demo
{
    public class ImageUriConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value != null)
            {
                return ImageSource.FromUri(new Uri(value.ToString()));
            }

            return null;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return value;
        }
    }
}


Set a static resource for your converter in page resource在页面资源中为转换器设置静态资源

Data Page Xaml数据页 Xaml

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:d="http://xamarin.com/schemas/2014/forms/design"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    xmlns:local="clr-namespace:demo"
    x:Class="demo.Data" x:Name="MyPage" >
    <ContentPage.Resources>
        <local:ImageUriConverter x:Key="imageConverter"></local:TestConverter>
    </ContentPage.Resources>

Converter usage with binding转换器使用绑定

<Image HeightRequest="300" Source="{Binding obj.avatar, Converter={StaticResource imageConverter}}"/>

You need to create another image property for ImageSource like below :您需要为 ImageSource 创建另一个图像属性,如下所示:

private ImageSource img;
    public ImageSource Img
    {
        get { return img; }
        set
        {
            img = value;
            OnPropertyChanged();
        }
    }

private UserDTO Obj;
    public UserDTO obj
    {
        get { return Obj; }
        set
        {
            Obj = value;
            OnPropertyChanged();
        }
    }

Now现在

 public Data(UserResponse result)
    {
        //show = test;
        InitializeComponent();
        obj = result.Data;
        if (!string.IsNullOrEmpty(obj.avatar))
        {
            Img = await getImageSource(obj.avatar);
        }

    }

and bind Img property to your XAML code like below :并将 Img 属性绑定到您的 XAML 代码,如下所示:

<StackLayout Padding="20, 60">
        <Label Text="Id" TextColor="Red" />
        <Editor BindingContext="{x:Reference Name=MyPage}" Text="{Binding obj.id}"   IsReadOnly="True" />
        <Label Text="First Name" TextColor="Red"/>
        <Editor BindingContext="{x:Reference Name=MyPage}" Text="{Binding obj.first_name}" IsReadOnly="True"/>
        <Label Text="Last Name" TextColor="Red"/>
        <Editor BindingContext="{x:Reference Name=MyPage}" Text="{Binding obj.last_name}" IsReadOnly="True"/>
        <Label Text="Email" TextColor="Red"/>
        <Editor BindingContext="{x:Reference Name=MyPage}" Text="{Binding obj.email}" IsReadOnly="True"/>
        <Editor BindingContext="{x:Reference Name=MyPage}" Text="Image" IsReadOnly="True"/>
        <Image BindingContext="{x:Reference Name=MyPage}" Source="{Binding Img}" HeightRequest="100" WidthRequest="100"/>



    </StackLayout>

Add below method to get image source:添加以下方法以获取图像源:

public async Task<ImageSource> getImageSource(string url)
    {
        byte[] byteArray = Client.DownloadData(url);
        return ImageSource.FromStream(() => new MemoryStream(byteArray));
    }

Now get image in Img现在在 Img 中获取图像

Img = await getImageSource(obj.avatar); img = await getImageSource(obj.avatar);

Output :输出 :

在此处输入图片说明

Hope it will help you希望它会帮助你

Thanks谢谢

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM