Architect's Log

I'm a Cloud Architect. I'm highly motivated to reduce toils with driving DevOps.

ディレクトリの子項目をリストボックスに表示する

アプリ実行


ソースコード

App.xaml
<Application x:Class="WpfApplication6.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             StartupUri="MainWindow.xaml">
</Application>
MainWindow.xaml
<Window x:Class="WpfApplication6.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:sx="clr-namespace:System.Xml;assembly=System.Xml"
        xmlns:l="clr-namespace:WpfApplication6"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <l:ToDirectoryChildrenConveter x:Key="toDirectoryChildrenConveter" />
    </Window.Resources>
    <ListBox ItemsSource="{Binding}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel>
                    <TextBlock Text="{Binding Path=FullName}" />
                    <!-- 内側のListBoxのItemSourceは子ディレクトリのコレクションになります -->
                    <ListBox Height="75" ItemsSource="{Binding Converter={StaticResource toDirectoryChildrenConveter}}">
                        <!-- 内側のListBox内の項目は単なるTextBlockになります -->
                        <ListBox.ItemTemplate>
                            <DataTemplate>
                                <TextBlock Text="{Binding Path=Name}" />
                            </DataTemplate>
                        </ListBox.ItemTemplate>
                    </ListBox>
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</Window>
MainWindow.xaml.cs
using System.IO;
using System.Windows;

namespace WpfApplication6 {
    public partial class MainWindow : Window {
        public MainWindow() {
            InitializeComponent();

            this.DataContext = new DirectoryInfo[] { new DirectoryInfo(@"c:\windows") };
        }
    }
}
ToDirectoryChildrenConveter.cs
using System;
using System.Globalization;
using System.IO;
using System.Windows.Data;

namespace WpfApplication6 {
    class ToDirectoryChildrenConveter : IValueConverter {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
            try {
                if (value is DirectoryInfo) {
                    return ((DirectoryInfo)value).GetDirectories();
                }
            }
            catch { }
            return null;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
            throw new NotImplementedException();
        }
    }
}