WPF ListBox SelectionChanged event

被刻印的时光 ゝ 提交于 2019-12-07 06:38:19

问题


I have a problem with listbox. When in my program I click on one ListBoxItem, I want to change/open the window and preorder it before. But the problem is that it firstly fires the event and then it changes selection. Code:

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());
            }
        }
    }

When I tried it with MessageBox.Show(LB_Playlist.SelectedIndex.ToString()); It was working, selection was changing but the message was showing. Is there any way to change it?


回答1:


The SelectionChangedEventArgs will contain which item was deselected and which item was selected. Use e.AddedItems to get the newly selected items. e.g.

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

This way you do not need to worry about whether the event is raised before or after the control being updated, but you do know the event args contain the correct information.




回答2:


With the MessageBox call, you likely allowed the UI to update, and change the selection before your code executed.

You should be able to remove the sleep, and use

File_Load_List(LB_Playlist.SelectedItem.Content.ToString(), _tempList);




回答3:


Solved. Just added Thread.Sleep(70); before try&catch.



来源:https://stackoverflow.com/questions/20025742/wpf-listbox-selectionchanged-event

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!