我正在尝试绑定到媒体元素,但所有尝试都失败了, 代码背后: -
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时,它正在工作但现在当我使用它后面的代码时它不再起作用,声音根本不起作用。 有什么帮助让这个工作吗? 感谢
答案 0 :(得分:3)
这里有几个问题。首先,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>