The objective of this technique is to create a control user interface
for the Silverlight MediaElement object. The controls
enable users to pause or stop the video to prevent the video images
on the MediaElement surface from moving, and stop
video-associated audio. These UI controls enable an interaction defined
in code event handlers. Each handler calls one of the following MediaElement methods:
Note that by default, a MediaElement will start playing
its media as soon as the UI loads completely AND the media source file
is downloaded (or a certain buffer size is reached, in the case of
streaming media). Use the AutoPlay property to change
this default.
This example has a UI definition in XAML and interaction logic in C#.
<UserControl x:Class="MediaElementControls.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
>
<Grid x:Name="LayoutRoot">
<StackPanel>
<MediaElement x:Name="media" Source="/xbox.wmv"
Width="300" Height="300"
AutomationProperties.Name="Video of new Fable game for XBox"
/>
<Grid Name="UIControls">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
<RowDefinition Height="20" />
</Grid.RowDefinitions>
<Button Click="StopMedia"
Grid.Column="0" Grid.Row="1" Content="Stop" />
<Button Click="PauseMedia"
Grid.Column="1" Grid.Row="1" Content="Pause" />
<Button Click="PlayMedia"
Grid.Column="2" Grid.Row="1" Content="Play" />
<Button Click="MuteMedia"
Grid.Row="2" Grid.Column="0" Content="Mute" />
<TextBlock Name="VolumeLabel" Grid.Row="2" Grid.Column="1" HorizontalAlignment="Right">Volume</TextBlock>
<Slider Height="20"
Value="{Binding Volume, Mode=TwoWay, ElementName=media}"
Minimum="0" Maximum="1"
Grid.Row="2" Grid.Column="2" Grid.ColumnSpan="2"
AutomationProperties.LabeledBy="{Binding ElementName=VolumeLabel}"/>
</Grid>
</StackPanel>
</Grid>
</UserControl>
private void StopMedia(object sender, RoutedEventArgs e)
{
media.Stop();
}
private void PauseMedia(object sender, RoutedEventArgs e)
{
media.Pause();
}
private void PlayMedia(object sender, RoutedEventArgs e)
{
media.Play();
}
private void MuteMedia(object sender, RoutedEventArgs e)
{
Button target = sender as Button;
// mute if not muted, unmute if already muted, in either case make sure the button content for text and accessibility info is updated
if (!media.IsMuted)
{
media.IsMuted = true;
target.Content = "Unmute";
}
else
{
media.IsMuted = false;
target.Content = "Mute";
}
}
This example is shown in operation in the working example of Media Element Controls.
MediaElement in the
user interface. #2 and #3 are true.
MediaElement