リストビューのサンプルとしてファイルの一覧を表示してみました。
ファイル名:NoXAML18ListView.csproj
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net8.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<UseWPF>true</UseWPF>
</PropertyGroup>
</Project>
ファイル名:App.cs
using System;
using System.Windows;
namespace NoXAML18ListView;
public class App : Application
{
[STAThread]
public static void Main(string[] args)
{
var app = new App();
app.Run();
}
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
var win = new MainWindow();
win.Show();
}
}
ファイル名:AssemblyInfo.cs
using System.Windows;
[assembly:ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
ファイル名:FileListView.cs
using System.Diagnostics;
using System.IO;
using System.Windows.Controls;
public class FileListView : ListView
{
string _currentDirectory;
public string CurrentDirectory
{
get
{
return _currentDirectory;
}
set
{
if (_currentDirectory == value) return;
_currentDirectory = value;
Update();
}
}
public FileListView()
{
_currentDirectory = Environment.CurrentDirectory;
this.InitializeView();
}
// ビューの初期化
private void InitializeView()
{
var gridView = new GridView();
// ヘッダーカラムの登録
gridView.Columns.Add(new GridViewColumn
{
Header = "名前",
DisplayMemberBinding = new System.Windows.Data.Binding("Name"),
Width = 300
});
this.View = gridView;
}
// 更新
public void Update()
{
var sw = Stopwatch.StartNew();
// 項目のクリア
this.Items.Clear();
List<FileItem> list = [];
// ファイルの一覧を取得
foreach (var e in Directory.EnumerateFileSystemEntries(CurrentDirectory))
{
// 項目の生成と追加
list.Add (new FileItem
{
Name = Path.GetFileName(e),
FullPath = e,
});
}
// 項目をリストビューに追加
this.ItemsSource = list;
sw.Stop();
Debug.Print($"{sw.ElapsedMilliseconds}ms");
}
// 項目クラス
private class FileItem
{
public string Name { get; set; } = "";
public string FullPath { get; set; } = "";
}
}
ファイル名:MainWindow.cs
using System.Windows;
using System.Windows.Controls;
namespace NoXAML18ListView;
public class MainWindow : Window
{
FileListView _fileListView;
public MainWindow()
{
this.Title = "NoXAML MainWindow";
this.Width = 400;
this.Height = 300;
this._fileListView = new FileListView();
this.Content = this._fileListView;
this.Loaded += (sender, e) =>
{
const string dir = @"J:\Pictures";
this._fileListView.CurrentDirectory = dir;
};
}
}
コメント