gpt4 book ai didi

c# - 为什么自动选择列表框的最后一项?

转载 作者:太空宇宙 更新时间:2023-11-03 12:40:46 24 4
gpt4 key购买 nike

当我使用此规则在列表框中打开或打开多个文件时

然后自动选择列表框的最后一项。 See

按照我的代码:

Xaml:

<ListBox x:Name="listbox4" Background="Salmon"   BorderBrush="Black" BorderThickness="3" Drop="listbox4_Drop"  >
</ListBox>

Xaml.cs:

private Dictionary<string, string> fileDictionary = new Dictionary<string, string>();   

private void load_Click(object sender, RoutedEventArgs e)
{
Microsoft.Win32.OpenFileDialog ofd = new Microsoft.Win32.OpenFileDialog();
ofd.DefaultExt = ".mp3";
ofd.Filter = "All|*.*";
ofd.Multiselect = true;
Nullable<bool> result = ofd.ShowDialog();
if (result == true)
{

for (int i = 0; i < ofd.FileNames.Length; i++)
{
var filePath = ofd.FileNames[i];
var fileName = System.IO.Path.GetFileName(filePath);
fileDictionary.Add(fileName, filePath);
listbox4.Items.Add(fileName);
listbox4.SelectedItem = fileName;
}
}
}

private void listbox4_Drop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{

string[] droppedFilePaths =
e.Data.GetData(DataFormats.FileDrop, true) as string[];

foreach (string droppedFilePath in droppedFilePaths)
{
var filePath = droppedFilePath;
var fileName = System.IO.Path.GetFileName(filePath);
fileDictionary.Add(fileName, filePath);
listbox4.Items.Add(fileName);
listbox4.SelectedItem = fileName;
}

}
}

但我想在加载或删除时自动选择加载的第一个项目。

注意:我说的不是喜欢

listbox4.SelectedIndex=0;

我说的是在加载或删除多个文件之间选择第一项。

这怎么可能?

最佳答案

要设置您必须在加载或删除之前获取列表中的项目总数,然后在添加文件之后,将 SelectedIndex 设置为下一个值。所以你的代码看起来像这样:

private void load_Click(object sender, RoutedEventArgs e)
{
var listCount = listbox4.Count;
Microsoft.Win32.OpenFileDialog ofd = new Microsoft.Win32.OpenFileDialog();
ofd.DefaultExt = ".mp3";
ofd.Filter = "All|*.*";
ofd.Multiselect = true;
Nullable<bool> result = ofd.ShowDialog();
if (result == true)
{
for (int i = 0; i < ofd.FileNames.Length; i++)
{
var filePath = ofd.FileNames[i];
var fileName = System.IO.Path.GetFileName(filePath);
fileDictionary.Add(fileName, filePath);
listbox4.Items.Add(fileName);
}
listbox4.SelectedIndex = listCount;
}
}

private void listbox4_Drop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
var listCount = listbox4.Count;
string[] droppedFilePaths =
e.Data.GetData(DataFormats.FileDrop, true) as string[];
foreach (string droppedFilePath in droppedFilePaths)
{
var filePath = droppedFilePath;
var fileName = System.IO.Path.GetFileName(filePath);
fileDictionary.Add(fileName, filePath);
listbox4.Items.Add(fileName);
}
if(droppedFilePaths.Any())
{
listbox4.SelectedIndex = listCount;
}
}
}

关于c# - 为什么自动选择列表框的最后一项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39086074/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com