I have a simple MediaPlayerElement defined in xaml and I would like to run some c# code when a user hits the play button on the transport controls but I can't find an event handle exposed to XAML to do that. Can it be done? ...
<MediaPlayerElement
Visibility="Visible"
x:Name="mp"
Source="C:/Users/Brian/Videos/happy.mp4"
AutoPlay="False"
AreTransportControlsEnabled="True"
Stretch="UniformToFill"
>
</MediaPlayerElement>
You need to use the MediaPlayer inside the MediaPlayerElement and subscribe to its CurrentStateChanged
:
this.MediaPlayerElementConrol.MediaPlayer.CurrentStateChanged += MediaPlayer_CurrentStateChanged;
and
private void MediaPlayer_CurrentStateChanged(MediaPlayer sender, object args)
{
if (sender.PlaybackSession.PlaybackState is MediaPlaybackState.Playing)
{
// Your logic here...
}
}
or if you need the Click
event of the play button, which is an AppBarButton
named PlayPauseButton:
this.MediaPlayerElementConrol.Loaded += MediaPlayerElementConrol_Loaded;
then
private void MediaPlayerElementConrol_Loaded(object sender, e)
{
if (this.MediaPlayerElementConrol.FindDescendant<AppBarButton>(x => x.Name is "PlayPauseButton") is AppBarButton playPauseButton)
{
playPauseButton.Click -= PlayPauseButton_Click;
playPauseButton.Click += PlayPauseButton_Click;
}
}
private void PlayPauseButton_Click(object sender, e)
{
if (this.MediaPlayerElementConrol.MediaPlayer.PlaybackSession.PlaybackState is Windows.Media.Playback.MediaPlaybackState.Paused)
{
// Your logic here...
}
}
NOTE:
FindDescendants
comes from the CommunityToolkit.WinUI.Extensions NuGet package.