views:

62

answers:

2

I need to perform some actions when list box selection is about to changed, but old item is still selected. Something like PreviewSelectionChanged. Does WPF allow such operation? I can not find such event in ListBox control.

A: 

What exactly do you need to do? You can normally just perform your work in the bound 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");
        }
    }
}

Of course, if you're binding to a dependency property, the same principal applies. The DependencyPropertyChanged handler gives you the old and new values.

HTH, Kent

Kent Boogaart
A: 

Here is how to get the old item from the selection changed 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're after.

Tri Q
Thank you for answer. It is just a part of my goal, another part is to prevent selection changing in some cases. OK, I think it's possible to check some conditions in the event handler and automatically restore old selection.
Alex Kofman