ListBox wpf SelectItem how to get in the code

ListBox lBox = new ListBox();
lBox.Items.Add("asdasd");
lBox.Items.Add("ыва23");
nb.Children.Add(lBox);

How do I get a highlighted Item from a list?

Author: Андрей NOP, 2017-10-13

2 answers

Use the property SelectedItem, for example:

MessageBox.Show((string)lBox.SelectedItem);

To track the change of the current element, subscribe to the event SelectionChanged:

lBox.SelectionChanged += lBox_SelectionChanged;

Example of a handler:

private void lBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    MessageBox.Show((string)lBox.SelectedItem);
}
 2
Author: Андрей NOP, 2017-10-13 12:23:28

If you do not use WPF and MVVM, then use the solution given by dear @Andrey. If you still use it, then do this:

XAML :

<Window x:Class="WpfApp1.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:WpfApp1"
    mc:Ignorable="d" Loaded="Window_Loaded"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <ListBox SelectedItem ="{Binding SelectedItem}" ItemsSource="{Binding ListBoxItemcColllections}" Margin="0,65,0,150"/>
    <Label Content="{Binding SelectedItem}" HorizontalAlignment="Center" VerticalAlignment="Top"/>
</Grid>

Event when loading the form:

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        this.DataContext = new ViewModel();
    }

The viewmodel class itself :

 class ViewModel : INotifyPropertyChanged
{
    public ObservableCollection<string> ListBoxItemcColllections { get; set; }
    private string selectedItem { get; set; }


    public string SelectedItem
    {
        get
        {
            return selectedItem;
        }
        set
        {
            selectedItem = value;
            NotifyPropertyChanged("SelectedItem");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
    public ViewModel()
    {
        ListBoxItemcColllections = new ObservableCollection<string>();
        ListBoxItemcColllections.Add("111");
        ListBoxItemcColllections.Add("222");
        ListBoxItemcColllections.Add("333");
    }
}

Result :

enter a description of the image here

enter a description of the image here

 1
Author: Сергей, 2017-10-13 11:13:39