开发者

How to get something like PreviewSelectionChanged event in ListBox?

I need to perform so开发者_如何学运维me 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.


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.


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.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜