WPF ListBox SelectionChanged事件

我有列表框的问题。 在我的程序中,我点击一个ListBoxItem,我想更改/打开窗口并预先订购它。 但问题是它首先触发事件然后改变选择。 码:

private void LB_Playlist_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (LB_Playlist.SelectedItem != null) { try { List _tempList = new List(); File_Load_List(LB_Playlist.SelectedItem.ToString(), _tempList); LoadListIntoBox(_tempList); G_SongList.Visibility = Visibility.Visible; AnimationMove(G_Playlist, G_Playlist.Margin, new Thickness(-264, 0, 0, 0), AnimationDuration, true); AnimationMove(G_SongList, new Thickness(264, 0, 0, 0), new Thickness(0, 0, 0, 0), AnimationDuration, false); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } } } 

当我用MessageBox.Show(LB_Playlist.SelectedIndex.ToString())尝试它时; 它正在发挥作用,选择正在改变,但信息正在显示。 有没有办法改变它?

SelectionChangedEventArgs将包含取消选择的项目以及选择的项目。 使用e.AddedItems获取新选择的项目。 例如

 var addedItems = e.AddedItems; if(addedItems.Count > 0) { var selectedItem = addedItems[0]; File_Load_List(selectedItem.ToString(), _tempList); } 

这样您就不必担心在更新控件之前或之后引发事件,但您确实知道事件args包含正确的信息。

使用MessageBox调用,您可能允许UI更新,并在代码执行之前更改选择。

你应该能够移除睡眠,并使用

File_Load_List(LB_Playlist.SelectedItem.Content.ToString(),_ tempList);

解决了。 刚刚添加了Thread.Sleep(70); 在尝试和捕获之前。