Home > database >  C# Mediaelement looping play in Itemtemplate
C# Mediaelement looping play in Itemtemplate

Time:10-05

I have a Usercontrol, with an Itemscontrol on it. This Itemscontrol has an Itemtemplate in a resource file.

<ItemsControl x:Name="itemcontrol" Grid.ColumnSpan="3" Grid.RowSpan="2"
    ItemsSource="{Binding PageItems}" 
    ItemTemplate="{StaticResource MosaicGridStyleMP4}" />

This template has a Mediaelement in it.

Mainskin.xaml:

<DataTemplate x:Key="MosaicGridStyleMP4">
<Border BorderBrush="Gray" BorderThickness="1" CornerRadius="10" Margin="2,2,2,2">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="60"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <TextBlock Text="{Binding PK_SpotABS}" Width="Auto" />
        <MediaElement x:Name="mePlayer" Source="{Binding Media.Source, Mode=OneWay}" Volume="0" Grid.row="1" />
    </Grid>
</Border>
</DataTemplate>

The video playing in the Mediaelement is working fine, except, it plays only once. How can I make it for infinite loop video playback? Even with the help of control buttons (Play, Stop, etc.).

( The Storyboard approach doesn't work. https://learn.microsoft.com/en-us/dotnet/desktop/wpf/graphics-multimedia/how-to-repeat-media-playback?view=netframeworkdesktop-4.8 )

CodePudding user response:

You could handle the MediaEnded event:

private void OnMediaEnded(object sender, RoutedEventArgs e)
{
    MediaElement mediaElement = (MediaElement)sender;
    mediaElement.Position = TimeSpan.Zero;
    mediaElement.Play();
}

XAML:

<MediaElement x:Name="mePlayer" Source="{Binding Media.Source, Mode=OneWay}" Volume="0" Grid.Row="1"
              UnloadedBehavior="Manual" MediaEnded="OnMediaEnded"/>
  • Related