How to get something like PreviewSelectionChanged event in ListBox?

I need to perform some actions when the list box selection changes soon, but the old item is still selected. Something like PreviewSelectionChanged. Does WPF provide such an operation? I cannot find such an event in a ListBox control.

+3
source share
3 answers

Here's how to get the old item from a modified select event.

private void ListBox_SelectionChanged(object sender , SelectionChangedEventArgs e)
{
    // Here are your old selected items from the selection changed.
    // If your list box does not allow multiple selection, then just use the index 0
    // but making sure that the e.RemovedItems.Count is > 0 if you are planning to address by index.
    IList oldItems = e.RemovedItems;

    // Do something here.

    // Here are you newly selected items.
    IList newItems = e.AddedItems;
}

Hope this is what you need.

+2
source

What exactly do you need to do? Usually you can just do your job in a related property:

<ListBox SelectedItem="{Binding SelectedItem}"/>

public object SelectedItem
{
    get { return _selectedItem; }
    set
    {
        if (_selectedItem != value)
        {
            // do some work before change here with _selectedItem

            _selectedItem = value;
            OnPropertyChanged("SelectedItem");
        }
    }
}

, , . DependencyPropertyChanged .

+1

the answer is not quite complete, the solution I found was:

Private NextSelectionChangedIsTriggeredByCode As Boolean = False
Private Sub MyListView_SelectionChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs)
    If NextSelectionChangedIsTriggeredByCode Then
        NextSelectionChangedIsTriggeredByCode = False
        Return
    End If
    If   ... Some reason not to change the selected item ...  Then
        Dim MessageBoxResult = MessageBox.Show("Changes were made and not saved. Continue Anyway ?", "Unsaved Changes", MessageBoxButton.OKCancel)
        If MessageBoxResult = MessageBoxResult.Cancel Then
            NextSelectionChangedIsTriggeredByCode = True
            MyListView.SelectedIndex = MyListView.Items.IndexOf(e.RemovedItems(0))
            Return
        End If
    End If

... Code to execute when selection could change ...

    e.Handled = True
End Sub
+1
source

Source: https://habr.com/ru/post/1719783/


All Articles