我的列表框有问题。在程序中单击一个ListBoxItem时,我想更改/打开该窗口并对其进行预排序。但是问题在于它首先触发事件,然后更改选择。代码:
private void LB_Playlist_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (LB_Playlist.SelectedItem != null)
{
try
{
List<string> _tempList = new List<string>();
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包含正确的信息。