有没有办法将图像从资产文件夹绑定到列表视图

时间:2019-01-07 05:57:20

标签: c# listview xamarin.forms binding

我有一个列表视图,我正在尝试将图像绑定到列表视图中。我可以执行它而没有任何错误,但是,列表无法显示图像。但是,我可以使用表视图实现相同的功能,并且图像在表视图中显示没有任何问题。但是我真的很想用列表视图来做到这一点。

我的xaml:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:TodoExample"
             x:Class="TodoExample.MainPage">

    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <StackLayout Orientation="Horizontal"
                     Margin="10,15,10,15" HorizontalOptions="Center">
            <Entry Placeholder="Enter the text here.."
                   x:Name="listValues"/>
            <Button x:Name="addButton" Text="+" FontAttributes="Bold" FontSize="Large"
                    Margin="10,0,0,0" Clicked="addButton_Clicked" WidthRequest="50"
                    HeightRequest="50"/>
        </StackLayout>

        <ListView x:Name="MyTodoList" Grid.Row="1" >
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <StackLayout Orientation="Horizontal"
                                     Margin="10,5,10,5" HorizontalOptions="CenterAndExpand">

                            <Label Text="{Binding Items}" VerticalOptions="Center"/>
                            <Image Source="{Binding MyImage}"/>
                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </Grid>

</ContentPage>

我的课程和属性:

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace TodoExample.Models
{
    public class MyItems
    {
        public string Items { get; set; }
        public ImageSource MyImage { get; set; }
    }

    public class ItemManager
    {
        public static List<MyItems> ItemsAdder(string itemName)
        {
            var item = new List<MyItems>();

            item.Add(new MyItems() { Items = itemName, MyImage = "/Assets/Clear.png" });
            return item;
        }
    }
}

我的主要班级:

namespace TodoExample
{
public partial class MainPage : ContentPage
{
    ObservableCollection<MyItems> NewList;
    public MainPage()
    {
        InitializeComponent();
        NewList = new ObservableCollection<MyItems>();
        MyTodoList.ItemsSource = NewList;
    }

    private void addButton_Clicked(object sender, EventArgs e)
    {
        //NewList.Clear();
        var newItems = ItemManager.ItemsAdder(listValues.Text);
        foreach (var item in newItems)
            NewList.Add(item);
    }
}
}

0 个答案:

没有答案