列表框SelectionChanged在函数wp7中设置为-1时触发

Sha*_*oty 3 listbox selectedindex silverlight-4.0 windows-phone-7

我在c#中遇到了一个非常奇怪的问题,我只是想知道是什么导致了这个问题.我有我的理论,但不完全确定,只是想看看它是否可以复制.

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>
Run Code Online (Sandbox Code Playgroud)

在我的C#中,我有以下内容:

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

这是问题所在:每当我点击三个listboxitems中的一个时,myhandle代码使选择等于正确的SelectedIndex,然后它击中该box.SelectedIndex =-1;行,然后refires是myhandle函数.这样做,选择现在为-1.

我不知道它为什么要回到堆栈.这不应该是递归函数.

我的目标是选择项目,然后将SelectedIndex返回-1,以便该人员能够在需要时再次选择该项目,而不是更改为另一个项目并返回.

当然有一个简单的解决方法是抛出一个switch函数并检查它是否已经-1,但这并不能解决递归的问题.

谢谢你的时间.

Cod*_*ked 8

每次更改选择时,都会触发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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


Dar*_*ide 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;
}
Run Code Online (Sandbox Code Playgroud)

不需要任何布尔处理程序,如果"-1"是当前索引,则该函数无效.所有这些都是为了弥补标准列表框的操作方式.

如果你使用MVVM并绑定到"Selecteditem"/"SelectedIndex"属性,你必须记住同样的事情.