0

我有很多.wav文件要播放,因此我创建了AudioItem类:

public class AudioItem
{
    public string SongName { get; set; }
    public string SongText { get; set; }

    public AudioItem()
    { }

    /// <summary>
    /// Initialize AudioItem class
    /// </summary>
    /// <param name="SongName">The name of the song(with .wav)</param>
    /// <param name="SongText">Text to display</param>
    public AudioItem(string SongName, string SongText)
    {
        this.SongName = SongName;
        this.SongText = SongText;
    }

    public void Play()
    {
        var stream = TitleContainer.OpenStream("Sound/" + SongName);
        var effect = SoundEffect.FromStream(stream);
        FrameworkDispatcher.Update();
        effect.Play();
    }

}

在视图中我有一个Listbox项目:

<ListBox Name="soundtrackLbx">
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <Button Name="ListButton" HorizontalAlignment="Stretch" >
                            <Button.Content>
                                <StackPanel Orientation="Horizontal">
                                    <Image Margin="10" Height="30" Width="30" Source="Picture/audio.png"/>
                                    <TextBlock Margin="10" HorizontalAlignment="Stretch" Text="{Binding SongText}" FontFamily="Verdana" Tap="TextBlock_Tap" />
                                </StackPanel>
                            </Button.Content>
                        </Button>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>

我背后的代码:

public ObservableCollection<AudioItem> AudioItems { get; set; }

    public MainView()
    {
        InitializeComponent();
        AudioItems = new ObservableCollection<AudioItem>();

        Initialize();
        this.soundtrackLbx.ItemsSource = AudioItems;
    }

    private void Initialize()
    {
        AudioItems.Add(new AudioItem("ApsolutnoDa.wav", "Apsolutno da"));
        AudioItems.Add(new AudioItem("Da.wav", "Da"));

    }

    private void TextBlock_Tap(object sender, GestureEventArgs e)
    {
        TextBlock tblock = sender as TextBlock;
        string text = tblock.Text;

        AudioItem item = AudioItems.SingleOrDefault(a => a.SongText == text);
        item.Play();
    }

好吧,.wav有时我会听到他们演奏,有时我不会,我不知道为什么会这样。

4

1 回答 1

0

好的。在这里,如果有人像我一样被困。问题是因为我将Tap事件设置在 上Textblock,而不是Button.

我是如何从中获取内容的Button.Content

我使用tag属性并将其绑定到SongName属性。

于 2012-04-07T10:39:41.497 回答