1

我正在尝试做我的第一个 WPF 项目,并且我已经开始使用这个示例项目来显示图像。其中一部分是将列表框绑定到图像数组的 XAML:

<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>

现在很好,但我想将它绑定到子文件夹中的所有图像,并且它是匹配模式的子文件夹。我的目录结构是这样的:

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

我想将列表框绑定到各种 Index.jpg 图像。

我通常的方法是使用 System.IO 和 Directory.GetFiles 做一些 CodeBehind,但由于 XAML 看起来相当强大,我只是想知道:这种类型的绑定可以完全在 XAML 中实现吗?

如前所述,WPF 的初学者,我想以“正确”的方式来做,这似乎是 DataBinding。

4

1 回答 1

4

从 WPF 的角度来看,“正确”的方式是这样的(分离代码和表示):

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

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

您仍然会使用绑定来绑定到 ListBox(在将 IndexReader 的集合实例设置为 ListBox 或其父项之一的 DataContext 之后):

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

规则是:如果不能轻易绑定,就不要尝试。

于 2010-01-15T06:34:58.787 回答