WPF: Binding a ItemsSource to a Directory

流过昼夜 提交于 2019-12-11 10:43:23

问题


I'm trying to do my first WPF project, and I've started with this sample project for image display. Part of it is the XAML that binds a Listbox to an Array of images:

<ListBox.ItemsSource>
    <x:Array Type="{x:Type ImageSource}">
        <ImageSource>http://static.flickr.com/34/70703587_b35cf6d9eb.jpg</ImageSource>
        <ImageSource>http://static.flickr.com/20/70703557_494d721b23.jpg</ImageSource>
        <ImageSource>http://static.flickr.com/35/70703504_3ebf8f0150.jpg</ImageSource>
        <ImageSource>http://static.flickr.com/35/70703474_18ef30450f.jpg</ImageSource>
    </x:Array>
</ListBox.ItemsSource>

Now that is nice, but I would like to bind it to all Images in a Subfolder and it's subfolders that match a pattern. My Directory structure is this:

Archive
    1994-01
        Index.jpg
        Page1.jpg
        ...
        PageN.jpg
    1994-02
        Index.jpg
        Page1.jpg
        ...
        PageN.jpg

I want to bind the Listbox to the various Index.jpg images.

My normal approach would be to do some CodeBehind using System.IO and Directory.GetFiles, but as XAML seems rather powerful, I'm just wondering: Can this type of binding be achieved entirely in the XAML?

As said, total beginner in WPF and I want to do it the "proper" way, which seems to be DataBinding.


回答1:


The "proper" way from the WPF standpoint would be this (separating code and presentation):

    public class IndexReader: INotifyPropertyChanged
    {
        public IEnumerable<string> IndexFiles 
            { get { ... } set { ... raise notify } }

        public void ReadIndexImagesFromFolder(string folder)
        {
...
        }
    }

you would still use binding to bind to the ListBox (after you set an set instance of IndexReader to DataContext of ListBox or one of its parents):

<ListBox ItemsSource="{Binding IndexFiles}"/>

The rule is: if it cannot be bound easily, do not attempt it.



来源:https://stackoverflow.com/questions/2069686/wpf-binding-a-itemssource-to-a-directory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!