WPF:绑定的ItemsSource到目录 [英] WPF: Binding a ItemsSource to a Directory
问题描述
我试图做我的第一个WPF项目,我已经开始与此示例项目一>用于图像显示。部分原因是结合一个列表框到图像阵列的XAML:
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
我要列表框绑定到不同的Index.jpg图像。
I want to bind the Listbox to the various Index.jpg images.
我的正常的做法是做使用System.IO和Directory.GetFiles一些codeBehind,但作为XAML看起来相当强大的,我只是想知道?可这类型的结合来在XAML完全实现
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?
至于说,在WPF总初学者,我想这样做的正确的方式,这似乎是数据绑定。
As said, total beginner in WPF and I want to do it the "proper" way, which seems to be DataBinding.
推荐答案
从WPF角度来看,正确的方式会是这样(分离code和presentation):
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)
{
...
}
}
您仍然会使用绑定来绑定到列表框(之后的IndexReader的实例集设置列表框的DataContext的或它的某个父):
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.
这篇关于WPF:绑定的ItemsSource到目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!