当我使用此规则删除或打开列表框中打开的多个文件时
按照我的代码:
的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;
我说的是在加载或删除多个文件之间选择第一项。
这怎么可能?
答案 0 :(得分:1)
要设置您必须在加载或删除之前获取列表中的总项数,然后在添加文件后,将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;
}
}
}