【发布时间】: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,我的错误。
-
嗯,很难说。难道是列表框有焦点,键盘动作触发了选择变化?