如何在ListBox中获得类似PreviewSelectionChanged事件的内容?

时间:2009-10-10 15:31:06

标签: wpf events wpf-controls

我需要在列表框选择即将更改时执行某些操作,但仍然选择旧项目。像PreviewSelectionChanged之类的东西。 WPF是否允许此类操作?我在ListBox控件中找不到这样的事件。

3 个答案:

答案 0 :(得分:2)

以下是如何从选择更改事件中获取旧项目。

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

希望这就是你所追求的目标。

答案 1 :(得分:1)

您到底需要做什么?您通常可以在绑定属性中执行您的工作:

<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处理程序为您提供旧值和新值。

答案 2 :(得分:1)

答案并不完全,我找到的解决方案是:

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