Search code examples
windows-phone-7silverlight-4.0listboxselectedindex

Listbox SelectionChanged firing when setting to -1 within function, wp7


I am running into a very odd problem in c# and I just wanted to know what is causing this. I have my theories, but not entirely sure and just want to see if it can be reproduced.

Standard Pivot Page in wp7 silverlight 4.

<Pivot>
  <PivotItem>
     <Listbox Width="400" Height="500" x:Name="box" SelectionChanged="myhandle">

        <ListBoxItem x:Name="item1">
           <TextBlock Height="40" Width="200" Text="hi everyone!"/>
        </ListBoxItem>

        <ListBoxItem x:Name="item2">
           <TextBlock Height="40" Width="200" Text="No Wai"/>
        </ListBoxItem>

        <ListBoxItem x:Name="item3">
           <TextBlock Height="40" Width="200" Text="Ya Rly!"/>
        </ListBoxItem>

     </Listbox>
  </PivotItem>
</Pivot>

In my C#, I have the following:

  private void myhandle(object sender, SelectionChangedEventArgs args)
  {
    var selection ="";
    selection = (sender as Listbox).SelectedIndex.ToString();
    box.SelectedIndex = -1;
  }

Here is the problem: Whenever I click on one of the three listboxitems, the myhandle code makes selection equal to the proper SelectedIndex, but then it hits the box.SelectedIndex =-1; line and then refires the myhandle function. In doing so, selection is now -1.

I have no idea why it is going back up the stack. This shouldn't be a recursive function.

My goal is to select the item, but then have the SelectedIndex back to -1 so that the person is able to select the item once again if need be, instead of changing to another item and back.

Sure there is an easy fix of throwing a switch function and checking to see if it's -1 already, but that doesn't solve the problem of the recursion.

Thanks for the time.


Solution

  • Everytime the selection is changed, the SelectionChanged event will fire. This includes clearing the selection, which includes setting SelectedIndex = -1 and even if you are already in a SelectionChanged handler.

    You can do something like this:

    private bool inMyHandle = false;
    private void myhandle(object sender, SelectionChangedEventArgs args)
    {
        if (!this.isMyHandle) {
            this.isMyHandle = true;
            try {
                var selection ="";
                selection = (sender as Listbox).SelectedIndex.ToString();
                box.SelectedIndex = -1;
            }
            finally {
                this.isMyHandle = false;
            }
        }
    }