绑定到媒体元素,

Binding to Media Element,

我正在尝试绑定到媒体元素,但我的所有尝试都失败了, 后面的代码:-

    private void myg_ItemClick(object sender, ItemClickEventArgs e)
    {
        string str = ((EgyGuide.Models.Arabic)e.ClickedItem).Sound;
        MediaElement m1 = new MediaElement();
        m1.Source = new System.Uri("ms-appx:///" + str);
        m1.Play();
    }

XAML:-

                <GridView x:Name="myg"
                      IsItemClickEnabled="True"
                      ItemClick="myg_ItemClick">
                <GridView.ItemTemplate>
                    <DataTemplate>
                        <Grid>
                            <StackPanel Orientation="Horizontal">
                                <TextBlock Text="{Binding English}"
                                           FontSize="22" />
                                <TextBlock Text="{Binding Arabia}"
                                           FontSize="22" />
                            </StackPanel>
                        </Grid>
                    </DataTemplate>
                </GridView.ItemTemplate>
            </GridView>

当我直接将源代码制作到我的 XAML 时,它可以正常工作,但现在当我在后面使用这段代码时,它不再起作用,根本无法播放声音。 有什么帮助让这个工作吗? 谢谢

这里有几个问题。首先,如果 MediaElement 不在 XAML 树中,它就不会播放 - 您需要添加它。其次,您不应立即调用 Play,而应等待引发 MediaOpened 事件。像这样:

代码:

MediaElement me;

private void StartButtonClicked(object sender, RoutedEventArgs e)
{
  me = new MediaElement();

  // Register for critical events. CurrentStateChanged is also useful
  me.MediaOpened += MediaElementMediaOpened;
  me.MediaFailed += MediaElementMediaFailed;

  // Start opening the file
  me.Source = new Uri("ms-appx:///Assets/WestEndGirls.wma");

  // Add to the XAML tree (assumes a Panel with the name "Root")
  Root.Children.Add(me);
}

// Errors will be reported here
void MediaElementMediaFailed(object sender, ExceptionRoutedEventArgs e)
{
  Debug.WriteLine(e.ErrorMessage);
}

// Only once the media has been opened can you play it
void MediaElementMediaOpened(object sender, RoutedEventArgs e)
{
  me.Play();
}

XAML:

<StackPanel x:Name="Root">
  <Button Content="Start" Click="StartButtonClicked" />
</StackPanel>