Get ListBox.SelectedItem with Class item in WPF

1 minute read

It may have already been mentioned, but as a memorandum.

I also wrote how to retrieve Selected Items
https://qiita.com/Michio029/items/3b531acd46bb1f81f7d7

Preparation

Prepare the list and contents
image.png

MainWindow.xaml


<Window><!--Window details are omitted-->
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="50"/>
        </Grid.RowDefinitions>
        
        <ListBox Grid.Row="0" Name="ExampleList" Margin="10" SelectionMode="Single" ScrollViewer.VerticalScrollBarVisibility="Auto">
            <!-- SelectionMode="Single": Only one can be selected from the list-->
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Text="{Binding Id, StringFormat=ID is{0} :}"/>
                        <TextBlock Text="{Binding Name, StringFormat=Name is{0} :}"/>
                        <TextBlock Text="{Binding Age, StringFormat=Age is{0}}"/>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
        <Button Grid.Row="1" Name="Btn" Content="button" Margin="100,10,100,10" Click="Btn_Click"/>
    </Grid>
</Window>

<textblock text="{binding id, stringformat=id is{0} :}"/>
You can read more about how to write the format of the string in this area here.
https://qiita.com/koara-local/items/815eb5146b3ddc48a8c3

c#:MainWindow.xaml.cs


public partial class MainWindow : Window
{
    List<ExampleClass> list = new List<ExampleClass>();
    public MainWindow()
    {
        InitializeComponent();

        list.Add(new ExampleClass() { Id = 0, Name = "aaa", Age = 10 });
        list.Add(new ExampleClass() { Id = 1, Name = "bbb", Age = 20 });
        list.Add(new ExampleClass() { Id = 2, Name = "ccc", Age = 30 });
        list.Add(new ExampleClass() { Id = 3, Name = "ddd", Age = 40 });
        list.Add(new ExampleClass() { Id = 4, Name = "eee", Age = 50 });
        ExampleList.ItemsSource = list;
    }

    private void Btn_Click(object sender, RoutedEventArgs e)
    {

    }
}
class ExampleClass
{
    public int Id { get; set; }
    public string Name { get; set; }
    public byte Age { get; set; }
}

Extract SelectedItem

Add the button processing.

    private void Btn_Click(object sender, RoutedEventArgs e)
    {
        //The selection item is 0=>Exit the method
        if (ExampleList.SelectedItems.Count == 0)
            return;

        //Extract as ExampleClass
        ExampleClass selitem = ExampleList.SelectedItem as ExampleClass;

        //Check the contents
        Console.WriteLine("Selected item Id:{0} Name:{1} Age{2}", selitem.Id, selitem.Name, selitem.Age);
    }



I will press the button
image.png

Execution result

Selected item Id:0 Name:aaa Age10

I was able to take it out.