wonea
wonea

Reputation: 4969

Capturing WPF Listbox checkbox selection

Been trying to figure out, how do I capture the events from a listbox. In the template, I've added the parameter IsChecked="" which starts my method. However, the problem is trying to capture what has been checked in the method. SelectedItem only returns what is currently selected, not the checkbox.

object selected = thelistbox.SelectedItem;
DataRow row = ((DataRowView)selected).Row;
string teststring = row.ItemArray[0].ToString();    // Doesn't return the checkbox!

<ListBox IsSynchronizedWithCurrentItem="True" Name="thelistbox" ItemsSource="{Binding mybinding}">
    <ListBox.ItemTemplate>
            <DataTemplate>
                    <StackPanel>
                            <CheckBox Content="{Binding personname}" Checked="CheckBox_Checked" Name="thecheckbox"/>
                        </StackPanel>
                </DataTemplate>
        </ListBox.ItemTemplate>
</ListBox>

Upvotes: 0

Views: 5452

Answers (1)

repka
repka

Reputation: 2979

Ideally you should bind IsChecked to a property on your row i.e.

<CheckBox Content="{Binding personname}" IsChecked="{Binding IsPersonChecked}" Name="thecheckbox"/>

where "IsPersonChecked" is column in your DataTable (or whatever you bind to), just like "personname". Then you can read whether it is checked directly from your DataRow variable:

DataRow row = ((DataRowView)thelistbox.SelectedValue).Row;
bool isPersonChecked = (bool) row["IsPersonChecked"];

If DataSet is typed, you want to use typed DataRow properties, obviously.

Note that I used SelectedValue, not SelectedItem property. I believe SelectedItem is actually an instance of ListBoxItem. Which you can use if you want to leave your IsChecked unbound. Then you'd have to retrieve CheckBox considering full template hierarchy. Something like:

bool isChecked = ((CheckBox)((StackPanel) ((ListBoxItem) thelistbox.SelectedItem).Content).Children[0]).IsChecked ?? false;

Messy. (Debug and adjust the hierarchy to what you'll actually get. My code wont probably work as is.)

Better approach is to use RoutedEventArgs of your CheckBox_Checked handler:

private void CheckBox_Checked(object sender, RoutedEventArgs e)
{
    CheckBox checkBox = (CheckBox) e.Source;
    DataRow row = ((DataRowView) checkBox.DataContext).Row;
    bool isChecked = checkBox.IsChecked ?? false;
}

Upvotes: 1

Related Questions