我创建了一个包含字典的列表框。
但我想删除项目列表框&点击一下字典。
代码:
的Xaml:
<ListBox x:Name="ListBoxPlayList" SelectionMode="Extended"/>
<Button x:Name="addbtn" Margin="2,5,41,5" Click="addbtn_Click" />
<Button x:Name="removebtn" Click="removebtn_Click" />
Xaml.cs:
public Dictionary<string, string> fileDictionary = new Dictionary<string, string>();
private void addbtn_Click(object sender, RoutedEventArgs e)
{
var listCount = ListBoxPlayList.Items.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);
ListBoxPlayList.Items.Add(fileName);
}
ListBoxPlayList.SelectedIndex = listCount;
}
}
我正在尝试使用此代码:
但是当我点击删除按钮时,项目从词典中移除但不从列表框中删除。
private void remove(object sender, RoutedEventArgs e)
{
var itemsToRemove = listbox4.SelectedItems;
foreach (var item in itemsToRemove)
{
fileDictionary.Remove(item.ToString());
listbox4.Items.Remove(item);
}
}
注意:
我想从列表框中删除项目&amp; fileDictionary立刻。
&安培;没有播放项目。
当我不使用字典时,此代码有效。
private void removebtn_Click(object sender, RoutedEventArgs e)
{
object[] itemsToRemove = new object[ListBoxPlayList.SelectedItems.Count];
ListBoxPlayList.SelectedItems.CopyTo(itemsToRemove, 0);
foreach (object item in itemsToRemove)
{
if (mediaelement.Source != new Uri(item.ToString())) //MediaPlayer source
ListBoxPlayList.Items.Remove(item);
}
}
问题:
如何从列表框中删除所选项目&amp;单击并忽略字典删除正在我的媒体元素上播放的项目?
答案 0 :(得分:1)
请您查看此代码吗?没有得到整个代码,我无法测试它。
private void removebtn_Click(object sender, RoutedEventArgs e)
{
object[] itemsToRemove = new object[ListBoxPlayList.SelectedItems.Count];
ListBoxPlayList.SelectedItems.CopyTo(itemsToRemove, 0);
foreach (var item in itemsToRemove)
{
fileDictionary.Remove(item.ToString());
ListBoxPlayList.Items.Remove(item);
}
}
答案 1 :(得分:1)
你快到了。在熟悉基础知识之前,请始终使用括号。请阅读下面的评论。
private void removebtn_Click(object sender, RoutedEventArgs e)
{
object[] itemsToRemove = new object[ListBoxPlayList.SelectedItems.Count];
ListBoxPlayList.SelectedItems.CopyTo(itemsToRemove, 0);
foreach (object item in itemsToRemove)
{
string filePath;
fileDictionary.TryGetValue(item.ToString(), out filePath);
if (mediaelement.Source != new Uri(filePath)) //MediaPlayer source
{ //you forgot the parenthesis for the if condition.
ListBoxPlayList.Items.Remove(item);//remove from list
fileDictionary.Remove(item.ToString());//remove from dictionary
}
}
}