简体   繁体   English

文本文件中的图片库

[英]Image Gallery from text file

I have a listbox and an image... 我有一个列表框和一个图片...

XAML XAML

<ListBox Name="listbox">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding}"></TextBlock>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>
<Image Source="{Binding ElementName=listbox,Path=selectedItem."TEXT SECOND LINE HERE"}" Height="300"/>

C# C#

FileOpenPicker picker = new FileOpenPicker();
picker.ViewMode = PickerViewMode.Thumbnail;
picker.SuggestedStartLocation = PickerLocationId.ComputerFolder;
picker.FileTypeFilter.Add(".txt");

StorageFile file = await picker.PickSingleFileAsync();

if (file != null)    {
    var stream = await file.OpenAsync(FileAccessMode.Read);
    using (StreamReader reader = new StreamReader(stream.AsStream()))
        {
            while (!reader.EndOfStream)
            {
                string line = reader.ReadLine();

                if (line.StartsWith("---") {
                    listbox.items.Add(line);
                }

This will open a text file like this: 这将打开一个文本文件,如下所示:

--- CAT
http://server.com/cat.png

--- DOG
http://server.com/dog.png

--- BIRD
http://server.com/bird.png

... and populate the listbox with just the animal; ...然后只用动物填充列表框; How can I get the second line of the text file to show the correct image on selected list item!? 如何获得文本文件的第二行,以在所选列表项上显示正确的图像!?

Any help would be great; 任何帮助都是很好的;

Thanks in advance!! 提前致谢!!

You can create a Model for Animals 您可以创建动物模型

class AnimalModel
{
    public string Name { get; set; }
    public string Url { get; set; }
}

and add them to a list while reading your file 并在阅读文件时将其添加到列表中

var animalList = new List<AnimalModel>();
...
var model = new AnimalModel();
if (line.StartsWith("---") {
    model.Name = line;
}
else if(line.StartsWith("http://") {
    model.Url = line;
}
animalList.Add(model);

This list you can then bind to the Listbox. 然后,您可以将此列表绑定到列表框。

listbox.ItemSource = animalList;

Change Text="{Binding}" to Text="{Binding Name}" , add a SelectionChanged event to the Listbox Text="{Binding}"更改为Text="{Binding Name}" ,向列表框中添加SelectionChanged事件

<ListBox Name="listbox" SelectionChanged="Listbox_SelectionChanged">

and get the selected model. 并获取所选模型。 Then change the image source to the selected one. 然后将图像源更改为选定的图像源。

private void Listbox_SelectionChanged(object sender, SelectionChangedEventArgs e) {
   var model = (sender as ListView)?.SelectedItem as AnimalModel;
   if(model != null)
       ImageName.Source = model.Url; // give the image a name to access it
}

I'm not sure if you can set a string as an Image Source, maybe you have to change this. 我不确定是否可以将字符串设置为图像源,也许您必须更改此设置。

How can I get the second line of the text file to show the correct image on selected list item!? 如何获得文本文件的第二行,以在所选列表项上显示正确的图像!?

If you don't have to use MVVM, the easiest way to let it work is to create a model class and bind a list of model instances to the listbox: 如果您不必使用MVVM,最简单的方法就是创建模型类并将模型实例列表绑定到列表框:

public sealed partial class MainPage : Page
{
    public List<Item> items;
    public MainPage()
    {
        this.InitializeComponent();
    }

    private async void btnClick_Click(object sender, RoutedEventArgs e)
    {
        FileOpenPicker picker = new FileOpenPicker();
        picker.ViewMode = PickerViewMode.Thumbnail;
        picker.SuggestedStartLocation = PickerLocationId.ComputerFolder;
        picker.FileTypeFilter.Add(".txt");

        StorageFile file = await picker.PickSingleFileAsync();

        if (file != null)
        {
            var stream = await file.OpenAsync(FileAccessMode.Read);
            using (StreamReader reader = new StreamReader(stream.AsStream()))
            {
                items = new List<Item>();
                while (!reader.EndOfStream)
                {
                    string line = reader.ReadLine();
                    if (line.StartsWith("---"))
                    {
                        //listbox.Items.Add(line);
                        //Instead of adding a line, add an item instance
                        items.Add(new Item
                        {
                            Name = line
                        });
                    }
                    else if(line!=string.Empty)//if it is not the empty line then add it to the last item's url
                    {
                        if (items.LastOrDefault() != null)
                        {
                            items.LastOrDefault().URL = line;
                        }
                    }
                }

                listbox.ItemsSource = items;
            }
        }
    }
}

public class Item
{
    public String Name { get; set; }

    public String URL { get; set; }
}

And the XAML: 和XAML:

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <ListBox Name="listbox">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Name}"></TextBlock>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
    <Image Source="{Binding ElementName=listbox,Path=SelectedItem.URL}" Height="300"/>
    <Button Name="btnClick" Click="btnClick_Click">Click Me</Button>
</Grid>

Here is the complete demo: ImageBindingSample . 这是完整的演示: ImageBindingSample

Notes: I use the Images inside the project. 注意:我在项目内部使用图像。 you can change it to online pictures. 您可以将其更改为在线图片。

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

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