views:

2057

answers:

1

I have a Listbox, that has a Checkbox as part of the item template.

In the click even of the Checkbox, I want to make sure that same list item is selected.

ListBoxItem lbi = ((ListBoxItem)listLayers.
                       ContainerFromElement((CheckBox)sender));
lbi.IsSelected = true;

The main issue that I'm having is that "ContainerFromElement" is not available in silverlight.

Any help is greatly appreciated.

edit

This is the code I'm running in the click event of a checkbox inside my list:

MyObject obj = listLayers.SelectedItem as MyObject;
obj.Visible = true;
obj.Value = "50";

Using the RelativeSource binding on the checkboxes along with this code, I end up with obj equal to null.

I have a list of layers that I want to turn on and off via checkboxes, I'm open to another way...

+3  A: 

In the selectionChanged event you have to "walk" the visual tree to find the checkbox. You can do this by using the VisualTreeHelper

This example show what you need to do to get to the checkbox.

Below are some other solutions to this problem

You should use a RelativeSource binding between the ListboxItem and the CheckBox. The datatemple contains a checkbox. Change it to look like this.

<CheckBox 
  IsChecked="{Binding RelativeSource={RelativeSource TemplatedParent}, 
    Path=IsSelected, Mode=TwoWay}" />

This creates a binding between the IsSelected property of the ListBox and the IsChecked property of the CheckBox. This tutorial explains how with an example.

If you need more control, you should have a look at behaviors and triggers. They're a bit more complex but give you you more control.

Sorskoot
This looks good, but either I don't get it enough to apply to my situation, or it isn't exactly what I'm looking for.
Nate Bross
I have tried this: "<CheckBox IsChecked="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=IsSelected, Mode=TwoWay}" />" But on the Click event handler the code I have above ends up being null.
Nate Bross
are you handling the click on the listbox or on the checkbox?
Sorskoot
On the Checbox.
Nate Bross
I think the click on the checkbox is handled before the listbox item is actually selected, which might give the wrong result. Have you tried handling the selectionChanged event on the listbox?
Sorskoot
Using SelectionChanged event is working; how can I check the value of the checkbox inside the current ListBoxItem?
Nate Bross