Skip to main content
 首页 » 编程设计

c#之WPF:将 ItemsSource 绑定(bind)到目录

2024年02月24日17tuyile006

我正在尝试做我的第一个 WPF 项目,我从 this sample project 开始用于图像显示。它的一部分是将列表框绑定(bind)到图像数组的 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> 

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

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

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

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

如前所述,我是 WPF 的新手,我想以“正确”的方式进行操作,这似乎是 DataBinding。

请您参考如下方法:

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

    public class IndexReader: INotifyPropertyChanged 
    { 
        public IEnumerable<string> IndexFiles  
            { get { ... } set { ... raise notify } } 
 
        public void ReadIndexImagesFromFolder(string folder) 
        { 
... 
        } 
    } 

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

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

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