2016-08-22 14 views
1

ListBoxにファイル名(絶対パスなし)を追加したいとします。Safefilenamesでメディアソースが機能しないのはなぜですか?

Like This

以下のコードは、スムーズに作業しますが、ときに私はそれはもう働いていない(アイテムの場所を隠すため)SafeFileNamesFileNamesを変更するとされます。

XAML

<MediaElement x:Name="mePlayer" Margin="64,0,90,61"/> 
<ListBox x:Name="listbox4" Background="Salmon" BorderBrush="Black" BorderThickness="3"/> 

CS

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++) 
     { 
      listbox4.Items.Add(ofd.FileNames[i].ToString()); 
      listbox4.SelectedItem = ofd.FileName; 
      mePlayer.Source = new Uri(
       listbox4.SelectedItem.ToString(), 
       UriKind.RelativeOrAbsolute); 
      mePlayer.LoadedBehavior = MediaState.Play;  
     }      
    } 
} 

答えて

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); 
       // not sure about this logic. You may need to reconsider what you are trying to do here. 
       //Instead of doing this, create a click event for the list box and get the selected file path to be played from the dictionary. 
       listbox4.Items.Add(fileName);     
      } 
     } 
    } 

private void listbox4_SelectionChanged(object sender, SelectionChangedEventArgs e) 
{ 
    if (listbox4.SelectedItem != null) 
    { 
     var selectedFile = listbox4.SelectedItem.ToString(); 
     string selectedFilePath; 
     fileDictionary.TryGetValue(selectedFile, out selectedFilePath); 
     if (!string.IsNullOrEmpty(selectedFilePath)) 
     { 
      mePlayer.Source = new Uri(selectedFilePath, UriKind.RelativeOrAbsolute); 
      mePlayer.LoadedBehavior = MediaState.Play; 
     } 
    } 
} 
+0

ロードされたファイルは1つのみです。 選択変更時にコードを書き込むと、そのコードは機能しません。 が、私はこのコードを書いた: 'ます。private void listbox4_SelectionChanged(オブジェクト送信者、SelectionChangedEventArgs E) { をするif(!listbox4.SelectedItem = NULL){ mePlayer.Source =新しいウリ(listbox4.SelectedItem.ToString()、 UriKind.RelativeOrAbsolute); mePlayer.LoadedBehavior = MediaState.Play; } } ' –

+0

これは間違いです。より多くのサンプルについては私の更新された答えを見てください。 –

+0

ありがとうございました。私はあなたを愛しています。 –

関連する問題