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

时间:2015-03-14 15:52:53

标签: c# winforms listbox

我在c#(winforms)中遇到了ListBox的问题。此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

我尝试对其进行调试,结果是,在FileList.SelectedIndex中设置this.SelectedPicture的值时,它保持为0,直到MainFormKeyDown返回。编辑:我忘了提及那时FileList.SelectedIndex更改为随机值而不是0-1

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

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

我也尝试使用ListView,但结果保持不变。

现在我没有想法。

1 个答案:

答案 0 :(得分:1)

如果列表框具有焦点,则可能是KeyDown事件触发用户释放密钥并触发KeyUp事件并且列表框更改其selectedIndex。您是否尝试过更改为KeyUp事件并设置

e.Handled = true;

Handled Property

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