Maura Monville

Maura Monville

  • 1.7k
  • 70
  • 6.1k

ListBox "Selected" event is not accepted by the C# compiler

Feb 23 2022 3:51 PM

Sorry to ask a silly question. 
The behavior of my WPF UI is driving me crazy.
I would like to be able to select the single items in a ListBox that displays a list of strings.

<ListBox x:Name="CTnames" Grid.Column="80" Grid.Row="5" Height="700" d:ItemsSource="{d:SampleData}"  ScrollViewer.VerticalScrollBarVisibility="Visible" ScrollViewer.CanContentScroll="True" Margin="20,10,560,100" Grid.ColumnSpan="16" SelectionMode="Single" Selected="CTnames_Selected" />

If I list the properties of the ListBox and click on the Event symbol (lightning bolt) I can see that "Selected" is a ListBox event. I double click on it and Visual Studio generates the method " private void CTnames_Selected(object sender, RoutedEventArgs e)"
       
Inside such a method I would like to get the index of the selected string in the ListBox. So I developed the following instructions:

 
public int CTindex 
        { get; set; }

private void CTnames_Selected(object sender, RoutedEventArgs e)
        {
            CTindex = CTnames.SelectedIndex;
        }

Unluckily, the compiler returns the following error in the XAML file at the line corresponding to the definition of the ListBox:

"Severity    Code    Description    Project    File    Line
Error    CS1061    'ListBox' does not contain a definition for 'Selected' and no accessible extension method 'Selected' accepting a first argument of type 'ListBox' could be found (are you missing a using directive or an assembly reference?)    WPF UI    C:\Users\mauram\Desktop\WPFDemo_Dapper\WPFUI\MainWindow.xaml    142

I cannot understand such an error because "Selected" is listed by Visual Studio as a ListBox event.

My goal is to get the index of the selected item and use it to get another list of strings that will be displayed in another ListBox.

Thank you in advance for your help


Answers (1)