2016-08-22 1 views
0

미디어 플레이어 용 재생 목록을 만듭니다. 그것은 하나의 파일 드롭을 일하고여러 항목 드롭이 목록 상자에서 작동하지 않는 이유는 무엇입니까?

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) 
     { 
     for (int i = 0; i < droppedFilePaths.Length; i++) 
      { 
       var filePath = droppedFilePaths[i]; 
       var fileName = System.IO.Path.GetFileName(filePath); 
       fileDictionary.Add(fileName, filePath); 
       listbox4.Items.Add(fileName); 
       listbox4.SelectedItem = fileName; 
      } 

     } 
    } 
} 

하지만 난 다음 여러 개의 파일을 삭제하는 동안은 목록 상자에 추가 아니에요 :

XAML :

<MediaElement x:Name="mePlayer" Margin="64,0,90,61" ></MediaElement> 
<ListBox x:Name="listbox4" Background="Salmon" BorderBrush="Black" BorderThickness="3" Drop="listbox4_Drop" > 
</ListBox> 
<Button x:Name="load" Content="Load" HorizontalAlignment="Left" VerticalAlignment="Top" Width="76" Click="load_Click" Margin="184,285,0,0"/> 

Xaml.cs

내 코드를 따르십시오.

로드 된 파일이 여러 개로드되었지만 여러 파일이 삭제되지 않습니다.

어떻게하면 여러 파일을 목록 상자에 드롭 할 수 있습니까?

+0

새 WPF 프로젝트에 코드를 붙여 넣고 여러 파일을 삭제하면 말하는 것처럼 작동합니다. 코드를 약간 수정해야하지만 전체적으로 "작동"했습니다. 그래서 당신이 직면 한 문제가 확실하지 않습니다. –

답변

1

내가 열거 한 문제를 복제 할 수 없어서 현재이 문제에 관해 귀하를 도와 드릴 수 없습니다. 그래도 내가 맞는 곳에서 내가 너를 도울 수있어.

현재 드롭 메소드에는 목록 상자에 추가하는 항목의 수를 배가시키는 추가 루프가 있습니다.

현재 방법 (foreach 문을 사용하여)

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) 
      { 
       //if you keep this loop, you will all the dropped files for each dropped file 
       //therefore, if I dropped 3 files, I'd get 9 entries in the listbox 
       //if I dropped 4 files, I'd get 16 entries and so on... 
       for (int i = 0; i < droppedFilePaths.Length; i++)//this has to go 
       {//this has to go 
        var filePath = droppedFilePaths[i];//this needs to be a different variable since "i" will no longer exist 
        var fileName = System.IO.Path.GetFileName(filePath); 
        //fileDictionary.Add(fileName, filePath); 
        listbox4.Items.Add(fileName); 
        listbox4.SelectedItem = fileName; 
       }//this has to go 

      } 
     } 
    } 

리팩토링

private void blaze_125_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; 
      } 

     } 
    } 

이도합니다 (ForLoop 사용) 일 것이다

private void blaze_125_listbox4_Drop_anotherSpin(object sender, DragEventArgs e) 
    { 
     if (e.Data.GetDataPresent(DataFormats.FileDrop)) 
     { 
      string[] droppedFilePaths = 
       e.Data.GetData(DataFormats.FileDrop, true) as string[]; 

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

슬리머

private void blaze_125_listbox4_Drop_Slimmer(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) 
      { 
       listbox4.Items.Add(System.IO.Path.GetFileName(droppedFilePath)); 
      } 
     } 
    } 

선택을 유지하거나 마지막을 선택하려면

private void UpdateTheListboxMaintainExistingSelection(Dictionary<string, string> incomingDictionary, ListBox listboxToModify) 
    { 
     var preSelectedItem = listboxToModify.SelectedItem;//store the current selection 

     listboxToModify.Items.Clear();//clear all the items in the list 
     foreach (KeyValuePair<string, string> item in incomingDictionary) 
     { 
      listboxToModify.Items.Add(item.Key); 
     } 
     //this method should probably be optimized because if your listBox already contains a large number of items 
     //it may be quicker to only add the missing items, instead of reverting back to an empty list, and adding all the items to it again. 
     //Though I'll leave this up to you to implement. We'll be here to answer questions if you have a hard time doing it. 

     //Maintain the selected item if there was one 
     if (preSelectedItem != null) 
     { 
      listboxToModify.SelectedItem = preSelectedItem; 
     } 
    } 

선택한 항목이있는 경우 선택한 항목을 유지하기 위해 목록

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

    private void blaze_125_listbox4_Drop_Slimmer(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) 
      { 
       //listbox4.Items.Add(System.IO.Path.GetFileName(droppedFilePath));//don't need this anymore 

       //Check if the file is already in the dictionary. 
       //Check by looking up the key, and by looking up the value too. 
       if (fileDictionary.ContainsKey(System.IO.Path.GetFileName(droppedFilePath)) || fileDictionary.ContainsValue(droppedFilePath)) 
       { 
        //no need to add this file, it's already in the dictionary 
        //if you try to add a file with a KEY identical to a KEY that already exists in the dictionary, 
        //it will throw an exception 
        //A dictionary can contain the same value multiple times, but it can not contain the same key more than once. 
       } 
       else 
       { 
        //the file is not listed in the dictionary, so lets add it 
        fileDictionary.Add(System.IO.Path.GetFileName(droppedFilePath), droppedFilePath); 
       } 
      } 
     } 

     //Now lets call the method in charge of updating the listbox 
     UpdateTheListbox(fileDictionary, listbox4); 
    } 

    private void UpdateTheListbox(Dictionary<string, string> incomingDictionary, ListBox listboxToModify) 
    { 
     listboxToModify.Items.Clear();//clear all the items in the list 
     foreach (KeyValuePair<string, string> item in incomingDictionary) 
     { 
      listboxToModify.Items.Add(item.Key); 
     } 
     //this method should probably be optimized because if your listBox already contains a large number of items 
     //it may be quicker to only add the missing items, instead of reverting back to an empty list, and adding all the items to it again. 
     //Though I'll leave this up to you to implement. We'll be here to answer questions if you have a hard time doing it. 
    } 

업데이트 방법을 항목을 저장하는 사전을 사용하여 업데이트 할 항목이없는 경우 항목

private void UpdateTheListboxMaintainExistingOrSelectLastAdded(Dictionary<string, string> incomingDictionary, ListBox listboxToModify) 
    { 
     var preSelectedItem = listboxToModify.SelectedItem;//store the current selection 

     listboxToModify.Items.Clear();//clear all the items in the list 
     foreach (KeyValuePair<string, string> item in incomingDictionary) 
     { 
      listboxToModify.Items.Add(item.Key); 
     } 
     //this method should probably be optimized because if your listBox already contains a large number of items 
     //it may be quicker to only add the missing items, instead of reverting back to an empty list, and adding all the items to it again. 
     //Though I'll leave this up to you to implement. We'll be here to answer questions if you have a hard time doing it. 


     if (preSelectedItem != null) 
     { 
      //Maintain the selected item if there was one 
      listboxToModify.SelectedItem = preSelectedItem; 
     } 
     else 
     { 
      //select the last item in the listbox if nothing was pre-selected 
      listboxToModify.SelectedItem = listboxToModify.Items[listboxToModify.Items.Count - 1]; 
     } 
    } 
+0

잘 작동합니다.하지만 ** 목록이 왜 마지막 항목을 선택합니까? ** –

+0

질문에 대한 답을 잘 모르겠습니다. 가치가있는 것을 위해 ForEach 및/또는 ForLoop을 조금 더 쉽게 슬림화 할 수 있습니다. 'filePath'와'fileName'은 실제로 필요하지 않습니다. 'listbox4.Items.Add (fileName)'은 목록 상자에 항목을 추가하는 곳이고'listbox4.SelectedItem = filename'은 목록 상자에서 활성 선택을 변경하는 곳입니다. –

+0

아래 투표자들만이 "투표"와 함께하기 위해 의견을 남기면 ... –

관련 문제