XAMLを使わないWPF入門05「ListViewとコレクションをバインドする方法」

コンピュータ

XAMLを使わないWPFでListViewとコレクションのバインディングを試して見ます。

サンプルコード

・プロジェクトの作成

dotnet new wpf -f net8.0 -n NoXAML05
cd NoXAML05
rm *.xaml
rm MainWindow.xaml.cs

ファイル名:NoXAML05.csproj

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>WinExe</OutputType>
    <TargetFramework>net8.0-windows</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <UseWPF>true</UseWPF>
    <!-- ↓追加 -->
    <StartupObject>NoXAML05.App</StartupObject>
  </PropertyGroup>

</Project>

ファイル名:MainWindowViewModel.cs

using System.Collections.ObjectModel;
using System.Windows;
using System.ComponentModel;
using System.Runtime.CompilerServices;

namespace NoXAML05;
public class MainWindowViewModel: INotifyPropertyChanged
{
    public event PropertyChangedEventHandler? PropertyChanged;
    protected void OnPropertyChanged([CallerMemberName] string? name = null) =>
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));

    private string _selectedItem = "";
    public string SelectedItem
    {
        get => _selectedItem;
        set
        {
            if (value == _selectedItem) return;

            _selectedItem = value;

            OnPropertyChanged();
        }
    }
    public ObservableCollection<string> Items { get; } = ["リンゴ", "バナナ", "オレンジ"];

    public MainWindowViewModel()
    {
        PropertyChanged += (sender, e) =>
        {
            if (e.PropertyName == "SelectedItem" && !string.IsNullOrEmpty(SelectedItem))
            {
                MessageBox.Show($"{SelectedItem}", "選択");
            }            
        };
    }
}

ファイル名:App.xaml.cs

using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;

namespace NoXAML05;

public partial class App : Application
{
    // エントリポイント
    [STAThread]
    public static void Main()
    {
        var app = new App();
        app.Startup += (sender, e) =>
        {
            var viewModel = new MainWindowViewModel();

            // ListView定義
            var listView = new ListView();

            // ItemsSourceにバインド
            var binding = new Binding(nameof(MainWindowViewModel.Items))
            {
                Source = viewModel
            };
            listView.SetBinding(ItemsControl.ItemsSourceProperty, binding);

            // SelectedItemにバインド
            var binding2 = new Binding(nameof(MainWindowViewModel.SelectedItem))
            {
                Source = viewModel,
                Mode = BindingMode.TwoWay
            };
            listView.SetBinding(ListView.SelectedItemProperty , binding2);

            // ウィンドウの構築と表示
            var window = new Window
            {
                Title = "ListViewバインド",
                Width = 400,
                Height = 300,
                DataContext = viewModel,
                Content = listView,
            };

            window.Show();

        };
        app.Run();
    }
}

動作イメージ

1.リストビューが表示されます。

2.項目を選択すると、メッセージボックスが表示される。

解説

サンプルコードはObservableCollectionをListViewのデータソースに、また、SelectedItemで選択された項目とバンドしています。

コメント