【问题标题】:WPF: Binding a ItemsSource to a DirectoryWPF:将 ItemsSource 绑定到目录
【发布时间】:2010-01-15 05:29:35
【问题描述】:

我正在尝试做我的第一个 WPF 项目,我已经开始使用 this sample project 进行图像显示。其中一部分是将列表框绑定到图像数组的 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

我想将 Listbox 绑定到各种 Index.jpg 图像。

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

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

【问题讨论】:

    标签: c# wpf xaml binding itemssource


    【解决方案1】:

    从 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}"/>
    

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

    【讨论】:

      猜你喜欢
      • 2011-01-14
      • 2017-09-18
      • 2011-08-23
      • 2015-04-07
      • 1970-01-01
      • 1970-01-01
      • 2011-12-17
      • 2011-10-26
      • 1970-01-01
      相关资源
      最近更新 更多