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

标签 c# wpf xaml binding itemssource

我正在尝试做我的第一个 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),就不要尝试。

关于c# - WPF:将 ItemsSource 绑定(bind)到目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2069686/

相关文章:

c# - 如何通过 Binding 在 Canvas 中显示项目

c# - 按钮不会触发 Click 事件

c++ - 使用 Composition API 通过 C++ UWP 应用程序在 XAML Canvas 上绘制对象

c# - 为什么在 XAML 中绑定(bind) MainWindow datacontext 无法像在代码隐藏中使用 this.datacontext=this 绑定(bind)一样?

c# - StackExchange.Redis 中是否提供原始命令?

c# - Panel.TabStop = true 没有效果

c# - 在所有情况下我都必须取消订阅所有事件吗?

c# - 如何访问在 Silverlight 4 的 App.xaml.cs 中创建的自定义属性

C# 动态添加按钮并用它发送事件参数

xaml - Xamarin.Forms 将网格的高度绑定(bind)到按钮的宽度