1. コレクションの準備とバインディング
まず、ObservableCollectionなどのバインディング可能なコレクションをコードビハインドで定義し、これをWPFのリストにバインディングします。
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows;
namespace YourNamespace
{
public partial class MainWindow : Window, INotifyPropertyChanged
{
private ObservableCollection<string> _items;
private string _selectedItem;
public ObservableCollection<string> Items
{
get => _items;
set
{
_items = value;
OnPropertyChanged(nameof(Items));
}
}
public string SelectedItem
{
get => _selectedItem;
set
{
_selectedItem = value;
OnPropertyChanged(nameof(SelectedItem));
}
}
public MainWindow()
{
InitializeComponent();
// コレクションにデータを追加
Items = new ObservableCollection<string> { "Item 1", "Item 2", "Item 3" };
// DataContextを設定
DataContext = this;
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
2. XAMLでのバインディング
次に、XAMLでリストにバインディングを設定します。ListBoxやComboBoxなど、選択可能なコントロールに対してItemsSourceとSelectedItemをバインドします。
<Window x:Class="YourNamespace.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="200" Width="200">
<Grid>
<ListBox ItemsSource="{Binding Items}"
SelectedItem="{Binding SelectedItem, Mode=TwoWay}" />
</Grid>
</Window>
3. コードビハインドで選択状態を監視
リスト内のアイテムが選択されると、SelectedItemプロパティが更新されるので、このプロパティの変更イベントを通じて選択を検知できます。
public string SelectedItem
{
get => _selectedItem;
set
{
if (_selectedItem != value)
{
_selectedItem = value;
OnPropertyChanged(nameof(SelectedItem));
// 選択変更時の処理をここに追加
MessageBox.Show($"選択されたアイテム: {_selectedItem}");
}
}
}
説明
ItemsプロパティはListBoxのアイテムソースとして使われ、XAMLでバインディングされています。SelectedItemプロパティを通じて、ユーザーがリストで選択したアイテムをコードビハインドで監視できます。SelectedItemのセッター内で選択変更時の処理を追加すれば、選択されたアイテムに応じた処理が可能です。
これで、リストの選択状態をコードビハインドで取得でき、選択が変更されるたびに任意の処理を実行できるようになります。


コメント