ファイラーその1
WPFのデータバインディング等が思ったより難解でちっともペースが上がらない。
手の込んだものを作るのは無理そうなので、
listboxの練習にfiler的なものを作ってみる。
FileView.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ComponentModel; using System.Collections.ObjectModel; using System.IO; namespace filer { // DataContextに使う class FileView : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; private void NotifyPropertyChanged(String propertyName = "") { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } private DirectoryInfo current_; // TextBox.Textにバインドする public String Path { get { return current_.FullName; } set { current_ = new DirectoryInfo(value); NotifyPropertyChanged("Path"); files_ = new ObservableCollection<FileSystemInfo>( current_.GetFileSystemInfos().ToArray()); } } private ObservableCollection<FileSystemInfo> files_ = new ObservableCollection<FileSystemInfo>(); // ListBox.ItemsSouceにバインドする public ReadOnlyObservableCollection<FileSystemInfo> Files { get { return new ReadOnlyObservableCollection<FileSystemInfo>(files_); } } public FileView(String path) { Path = path; } } }
MainWindow.xaml
<Window x:Class="filer.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:IO="clr-namespace:System.IO;assembly=mscorlib" Title="Filer" Height="350" Width="525"> <Window.Resources> <!-- Directory向け --> <DataTemplate DataType="{x:Type IO:DirectoryInfo}"> <Label Content="{Binding Path=Name}" Foreground="#FF2222"/> </DataTemplate> <!-- File向け --> <DataTemplate DataType="{x:Type IO:FileInfo}"> <StackPanel Orientation="Horizontal"> <Label Width="100" Content="{Binding Path=Name}"/> <Label Width="100" Content="{Binding Path=Length}"/> </StackPanel> </DataTemplate> </Window.Resources> <Grid> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition Height="*" /> </Grid.RowDefinitions> <TextBox Grid.Row="0" Name="currentFolder" Text="{Binding Path=Path}" /> <ScrollViewer Grid.Row="1" > <ListBox Name="currentFolderFiles" ItemsSource="{Binding Path=Files}"> <!-- Resourcesで定義したDataTypeつきのDataTemplateが自動的に選択される --> </ListBox> </ScrollViewer> </Grid> </Window>
DataTemplateのDataTypeを利用してlistboxのitemの種類に応じて、動的に適用するDataTemplateを変える手法を使っている。
この方法を使うには、DataTemplateをResoucesに配置することが必要。
MainWindow.xaml.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace filer { /// <summary> /// MainWindow.xaml の相互作用ロジック /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); DataContext=new FileView("C:\\"); } } }