0

我正在尝试创建一个从ListBox继承的类并将属性PreviousSelectedIndex添加到它。到目前为止一切都很好。

接下来,我试图在SelectedIndex更改之前设置该属性。

问题是我找不到属性SelectedIndex更改的方法,因此我可以捕获它。我总是可以在对象本身上手动更改它,但这只是一种解决方法。这是我得到的:

public class MyListBox : System.Windows.Forms.ListBox
{
    public int PreviousSelectedIndex { get; set; }

    public MyListBox() : base()
    {
        this.PreviousSelectedIndex = -1;
    }

    protected override void OnClick(EventArgs e)
    {
        this.PreviousSelectedIndex = base.SelectedIndex;
        base.OnClick(e);
    }
}

当我尝试时:

MessageBox.Show(
            "Previous Index = " + listBox4.PreviousSelectedIndex +
            "\nCurrent Index = " + listBox4.SelectedIndex
            );

我总是得到相同的值。

我也尝试了OnMouseDown()OnSelectedIndexChanged(),但没有成功。

4

1 回答 1

4

对于 Winform,您可以执行以下操作:

public class MyListBox : System.Windows.Forms.ListBox
{
    private int _selectedIndex = -1;
    public int PreviousSelectedIndex { get; set; }

    public MyListBox() : base()
    {
        this.PreviousSelectedIndex = -1;
        this.SelectedIndexChanged += OnSelectedIndexChanged;
    }

    private void OnSelectedIndexChanged(object sender, System.EventArgs e)
    {
        PreviousSelectedIndex = _selectedIndex;
        _selectedIndex = this.SelectedIndex;
    }
}

如果要改成WPF,可以从ListBox的SelectedChanged事件中获取上一项

public MyListBox() : base()
{
    this.SelectionChanged += OnSelectionChanged;
    this.PreviousSelectedIndex = -1;
}

private void OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
    if(e.RemovedItems.Count == 0)
    {
        this.PreviousSelectedIndex = -1;
    }
    else
    {
        this.PreviousSelectedIndex = this.Items.IndexOf(e.RemovedItems[0]);
    }
}
于 2012-06-23T20:03:41.230 回答