MediaElement control in Silverlight

Share on TwitterShare on TumblrSubmit to StumbleUponSave on DeliciousDigg This

In this article we are going to look at one of the media controls in silverlight “MediaElement”.

 <Grid x:Name="LayoutRoot" Background="Bisque" Height="450" Width="600">
            <ColumnDefinition Width="400" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
        <MediaElement MouseLeftButtonUp="mediaVideo_MouseLeftButtonUp" AutoPlay="False" Grid.Row="0" Grid.Column="0" HorizontalAlignment="Left" Margin="10,10,0,0" Name="mediaVideo" VerticalAlignment="Top" Width="300" Height="300" Source="Wildlife.wmv" />
        <Button Content="Play" Grid.Row="2" Height="23" HorizontalAlignment="Left" Margin="10,10,0,0" Name="btnPlay" VerticalAlignment="Top" Width="75" Click="btnPlay_Click" />

As shown in the above code drag and drop a MediaElement control in the grid and set its following properties:
Source=”Wildlife.wmv” – This is the important property to be set which tells the MediaElement which media file to be played. We need to make sure that the media file “Wildlife.wmv” is located in root of the silverlight project and “Buid Action” property of this media file is set to resource.

AutoPlay=”False” – By default this property value is true that means when the page is rendered the media starts playing. We set it to false so that the media is played based on user interest.

This causes the event “mediaVideo_MouseLeftButtonUp” to be fired when user performs the MouseLeftButtonUp action on the media element. which causes the media file(Audio/Video) to pause or resume playing based on the current state.
Grid.Row=”0″ Grid.Column=”0″ causes the UI element to be diplayed at row 0 and column 0 of the Grid.
Name=”mediaVideo” to identify the media file in the code file.
Width=”300″( optional-based on the requirement)
Height=”300″ (optional-based on the requirement)

code to be placed in the code-behind file:

  private void btnPlay_Click(object sender, RoutedEventArgs e)
            //Play the video when user clicks the Play button.

        private void mediaVideo_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
            //Toggles the CurrentState of the mediaVideo that is
            //If the media is playing it pauses and if it is in paused state it is played.
            if (mediaVideo.CurrentState == MediaElementState.Playing)

Now run the project (Ctrl +F5) and see the output.