I am currently working on a C# wpf project. I have a listbox and I am dynamically adding checkboxes to the listbox with the following code.
while (reader.Read())
{
Console.WriteLine("Database: " + reader.GetString("Database"));
string databaseName = reader.GetString("Database");
CheckBox chkDatabase = new CheckBox();
chkDatabase.Content = databaseName.Replace("_", "__");
chkDatabase.Uid = "chk_" + reader.GetString("Database");
chkDatabase.Checked += new RoutedEventHandler(chkDatabase_Checked);
lstDatabase.Items.Add(chkDatabase);
}
This is working fine and I the routedeventhandler works fine to determine when a check box has been selected or not.
What I want to be able to do is to allow the user to click on the row that the checkbox is in, instead of actually checking the row. I’ve added an event handler to the list box for the selection changed like the following:
private void lstDatabase_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Console.WriteLine("Selection Changed");
ListBox checkbox = (ListBox)e.Source;
Console.WriteLine("Checkbox2: " + checkbox.SelectedValue);
}
How can I get the checkbox value from the selection changed event handler.
Thanks for any help you can provide.
To get the checkbox itself we simply cast the selected item (which will be a checkbox as you have only added checkboxes to the listbox’s item) to checkbox.
Then we simply get the checkvalue using
Put that code inside you SelectionChanged function and you’ll retrieve the checkbox value. You can also set it there too.
I hope this helps.
EDIT:
However I would suggest running this code on a different event. If a user clicks on the already selected item in order to toggle the checkbox, a SelectionChanged event will NOT fire. I would suggest MouseUp, provided you test that there is actually a selectedItem before running the code.