【问题标题】:C#: ListBox SelectedIndex changes itself when method returnsC#:ListBox SelectedIndex 在方法返回时自行更改
【发布时间】:2015-03-14 15:52:53
【问题描述】:

我对 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

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

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

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

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

现在我没有主意了。

【问题讨论】:

  • MainFormKeyDown 挂接到 MainForm 中的什么事件?
  • 我不明白: MainFormKeyDown 更改 SelectedDirectory 。这会触发设置器。这里 this.SelectedPicture 被改变,触发它的设置器。你有 FileList.SelectedIndex = value;没有?
  • @TaW 我忘了提到 FileList.SelectedIndex 更改为 random value 而不是 0-1它应该。对不起。
  • @kmcnamee KeyDown 事件,编辑帖子以适应 KeyDown,我的错误。
  • 嗯,很难说。难道是列表框有焦点,键盘动作触发了选择变化?

标签: c# winforms listbox


【解决方案1】:

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

e.Handled = true;

Handled Property

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

【讨论】:

  • 您的解决方案效果很好。问题是它切换到一个名称以我在键盘上按下的字母开头的项目以切换到该目录。你可以每天学习新的东西,感谢这个:)
猜你喜欢
  • 2014-05-03
  • 1970-01-01
  • 2012-06-04
  • 2021-06-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多