Reputation: 38
I am trying to bind to a media element and all my tries failed, Code behind :-
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>
When i made the source directly to my XAML it was working but now when i used this code behind it doesn't work anymore, sound doesnt play at all. Any help getting this to work please? Thanks
Upvotes: 0
Views: 1528
Reputation: 12019
There are a couple of issues here. First, MediaElement
won't play if it isn't in the XAML tree - you need to add it. Second, you shouldn't immediatelly call Play
, but instead you should wait for the MediaOpened
event to be raised. Something like this:
Code:
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>
Upvotes: 3