Event Handling (Finally!)
Note carefully that we did, in fact, wire up an event handler for when the user changes the selected item in the listbox:
SelectionChanged="PresPhotoListBox_SelectionChanged"
This is typically done by clicking on an image (though you can accomplish this with the arrow keys as well!). This will fire the event handler in the code-behind file, which is, finally, C#. Remember C#? This is a book about C# (apologies to Arlo Guthrie).
The event handler is, as you would expect, in the code-behind file, Window1.xaml.cs:
private void PresPhotoListBox_SelectionChanged(
object sender, SelectionChangedEventArgs e)
{
ListBox lb = sender as ListBox;
if (lb != null)
{
if (lb.SelectedItem != null)
{
string chosenName = (lb.SelectedItem as ImageURL).Name.ToString( );
Title = chosenName;
}
}
else
{
throw new ArgumentException(
"Expected ListBox to call selection changed in " +
"PresPhotoListBox_SelectionChanged");
}
}Like all event handlers in .NET, you receive two parameters: the sender (in this case, the listbox) and an object derived from EventArgs.
In the code shown, we cast the sender to the listbox (and consider it an exception if the sender is not a listbox, as that is the only type of object that should be sending to this event handler).
We then check to make sure that the selectedItem is not null (during startup it is possible that it can be null). Assuming it is not null, we cast the selectedItem to an ImageURL, extract the Name property, and assign it to a temporary ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access