本ページは広告が含まれています。気になる広告をクリック頂けますと、サーバ運営費になります(^^
L_box01(リストボックス)のDataContextにバインディングしたコレクションを、逆にリストボックスが選択された時にその選択されたアイテムを取得し表示する方法です。
ListboxのSelectionChangedイベントを利用
private void L_box01_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Person per = (Person)L_box01.SelectedItem;
MessageBox.Show( " You selected " + per.Name + ".");
}
解説
L_box01.SelectedItem にてバインディンされたコレクションの選択された要素を指定できます。
Xaml
<Window x:Class="バインディング2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:バインディング2"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<ListBox x:Name="L_box01"
ItemsSource="{Binding}" Margin="0,0,0,49" SelectionChanged="L_box01_SelectionChanged">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Name}" />
<TextBlock Text="{Binding Age}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Button x:Name="button" Content="Button" HorizontalAlignment="Left" Margin="61,279,0,0" VerticalAlignment="Top" Width="75" Click="button_Click"/>
<Button x:Name="button1" Content="Button" HorizontalAlignment="Left" Margin="160,279,0,0" VerticalAlignment="Top" Width="75" Click="button1_Click"/>
</Grid>
</Window>
C#
namespace バインディング2
{
/// <summary>
/// MainWindow.xaml の相互作用ロジック
/// </summary>
public partial class MainWindow : Window
{
private ObservableCollection<Person> people;
public MainWindow()
{
InitializeComponent();
// DataContextにPersonのコレクションを設定する
this.people = new ObservableCollection<Person>(Enumerable.Range(1, 100)
.Select(x => new Person
{
Name = "tanaka" + x,
Age = (30 + x) % 50
}));
L_box01.DataContext = people;
}
public class Person
{
public string Name
{
get;
set;
}
public int Age
{
get;
set;
}
}
private void button_Click(object sender, RoutedEventArgs e)
{
// コレクションに要素を追加する。
this.people.Insert(0, new Person { Name = "追加したtanaka", Age = 100 });
}
private void button1_Click(object sender, RoutedEventArgs e)
{
// 全削除
this.people.Clear();
}
private void L_box01_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Person per = (Person)L_box01.SelectedItem;
MessageBox.Show( " You selected " + per.Name + ".");
}
}
}
バインディングの仕方はこちら
https://www.techlive.tokyo/archives/1987

