3

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.

4

3 回答 3

9

每次更改选择时,将触发 SelectionChanged 事件。这包括清除选择,包括设置 SelectedIndex = -1,即使您已经在 SelectionChanged 处理程序中。

你可以这样做:

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;
        }
    }
}
于 2011-10-06T19:53:46.637 回答
6

标准 MS 示例已经在标准列表框选定项事件中具有此功能。

只需在事件处理程序代码中使用以下内容:

    private void ListBox_SelectionChanged(object sender,System.Windows.Controls.SelectionChangedEventArgs e)
{
    // If selected index is -1 (no selection) do nothing
    if (ListBox.SelectedIndex == -1)
        return;

    //Do Something

    // Reset selected index to -1 (no selection)
    ListBox.SelectedIndex = -1;
}

不需要任何布尔处理程序,如果“-1”是当前索引,则该函数什么都没有。所有这些都是为了补偿标准列表框的操作方式。

如果您使用 MVVM 并绑定到“Selecteditem”/“SelectedIndex”属性,则必须记住同样的事情。

于 2011-10-07T11:25:09.020 回答
4

您也可以检查 args.AddedItems.Count :

private void myhandle(object sender, SelectionChangedEventArgs args) 
{
   if (args.AddedItems.Count > 0)
   {
       ....
       box.SelectedIndex = -1;
   }
}
于 2012-11-09T12:30:46.720 回答