0

如何从stations.xml 中提取URL 以在ListBox (MouseDoubleClick) 中播放?

我的代码

XAML

<Window x:Class="WpfApplication6.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApplication6"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <ListBox x:Name="listBox" HorizontalAlignment="Left" Height="220" Margin="20,30,0,0" VerticalAlignment="Top" Width="150" MouseDoubleClick="mylistbox"/>
    </Grid>
</Window>

这是我的 XML 文件 station.xml

<?xml version="1.0" encoding="utf-8"?>
<stations>
  <station url="http://onair.eltel.net:80/europaplus-128k" id="0">EuropaPlus2</station>
  <station url="http://online.radiorecord.ru:8101/rr_128" id="1">RRadio</station>
  <station url="http://radio.kazanturl-fm.ru:8000/mp3" id="2">Kazanturl</station>
  <station url="http://stream.kissfm.ua:8000/kiss" id="3">Kiss FM</station>
  </stations>

С#代码 在此处输入链接描述

4

1 回答 1

0

您正在使用不包含“url”属性的字符串填充 ListBox。一种选择是更改您的 LoadStations() 方法以将整个 XmlNode 添加到 ListBox 项。默认显示内部文本(电台名称)。

public void LoadStations()
{
     string fileName = "data.xml";
     if (File.Exists(fileName))
     {
         XmlDocument xmlDoc = new XmlDocument();

         xmlDoc.Load(fileName);
         XmlNodeList stationNodes = xmlDoc.SelectNodes("//stations/station");
         foreach (XmlNode stationNode in stationNodes)
         {
              listBox.Items.Add(stationNode); // by default, the InnerText will be displayed                
         }

         xmlDoc.Save(fileName); 
    }
    else
    {
         MessageBox.Show(" ");
    }
}

然后,您可以像这样在 MouseDoubleClick 处理程序中提取“url”属性:

private void mylistbox(object sender, MouseButtonEventArgs e)
{            
   XmlNode selectedNode = listBox.SelectedItem as XmlNode;
   string url = selectedNode.Attributes["url"].Value;
   MessageBox.Show(url);
   Play(url);
}

此外,如果可能,您可能需要考虑使用 WPF 数据绑定从 XML 文件加载 ListBox 项。您可以通过将 ListBox 绑定到 XAML 中的 XML 文件来删除您的 LoadStations() 方法。像这样的东西:

<Grid>
  <Grid.Resources>
    <XmlDataProvider x:Key="StationsXml" Source="stations.xml" />  
  </Grid.Resources>

  <ListBox HorizontalAlignment="Left" Height="220" Margin="20,30,0,0" 
       VerticalAlignment="Top" Width="150"            
       ItemsSource="{Binding Source={StaticResource StationsXml}, XPath=stations/station}"
       MouseDoubleClick="mylistbox"
          />
</Grid>
于 2016-02-02T16:06:02.040 回答