C#:ListBox SelectedIndex 在方法 returns 时自行更改

C#: ListBox SelectedIndex changes itself when method returns

我对 c#(winforms) 中的 ListBox 有疑问。此列表框包含指定目录中的文件列表(仅图片),如下所示:

private ListBox FileList = new ListBox();
private List<string> Directories = new List<string>
{
  @"some path",
  @"some other path",
  @"..."
};
private List<string> Pictures;

private int selectedDirectory = 0;
public int SelectedDirectory
{
  get { return selectedDirectory; }
  set
  {
    //the list of pictures is returned correctly
    Pictures = GetPictures(Directories[value]); 
    selectedDirectory = value;
    EventHandler handler = this.DirectoryChanged;
    // noone who subscribed to the event
    // changes FileList.SelectedItem or FileList.SelectedIndex
    if(handler != null)
      handler(this, EventArgs.Empty);
    this.SelectedPicture = Pictures.Count == 0 ? -1 : 0;
  }


this.DirectoryChanged += (sender, e) =>
{
  FileList.Items.Clear();
  FileList.Items.AddRange(Pictures);
};

private int selectedPicture
public int SelectedPicture
{
  get { return selectedPicture; }
  set
  {
    selectedPicture = value;
    if(value != -1)
      PictureBox1.Load(Pictures[value]);
    FileList.SelectedIndex = value;
  }
}

// after this method returns, FileList.SelectedIndex changes to a random value depending on what Directory was selected before the change
private void MainFormKeyDown(object sender, KeyEventArgs e)
{
  if(e.KeyCode == Keys.NumPad5)
    SelectedDirectory --;
  if(e.KeyCode == Keys.NumPad2)
    SelectedDirectory ++;
} // the value of SelectedIndex changes after leaving this exact line

我尝试调试它,结果是从 this.SelectedPicture 中设置 FileList.SelectedIndex 的值一直为 0,直到 MainFormKeyDown 返回。编辑:我忘了提到那一点 FileList.SelectedIndex 更改为随机值而不是 0-1 应该的。

什么会导致这种行为,我该如何解决?

我已经检查过我是否更改了代码中其他地方或任何事件订阅中的值,但没有。

我也试过用ListView,结果还是一样。

现在我没主意了。

如果列表框有焦点,则可能是 KeyDown 事件触发,用户放开按键,KeyUp 事件触发,列表框更改其 selectedIndex。您是否尝试更改为 KeyUp 事件并设置

e.Handled = true;

Handled Property

如果我按住键,KeyDown 会触发几次。你可以放一个 Debug.WriteLine 来查看如果你按住一个键它会触发几次。使用 KeyUp 的另一个原因。