Skip to content

Make MediaPlayerElement.MediaPlayer properties accessible via XAMLΒ #3425

@GSonofNun

Description

@GSonofNun

Describe the problem this feature would solve

When using a MediaPlayerElement in XAML, there were a couple properties on MediaPlayerElement's MediaPlayer instance I wanted to set/bind in XAML.
The properties I needed to set were IsLoopingEnabled and IsMuted.
<MediaPlayerElement IsMuted="True" IsLoopingEnabled="True"/>
However, these properties aren't available on MediaPlayerElement.

Describe the solution

The solution I ended up creating was using behaviors to set the properties on the MediaPlayer. Using them in XAML would look like this:

<MediaPlayerElement>
    <Interactivity:Interaction.Behaviors>
        <local:AutoRepeatBehavior AutoRepeat="True"/>
    </Interactivity:Interaction.Behaviors>
</MediaPlayerElement>
public class AutoRepeatBehavior : BehaviorBase<MediaPlayerElement>
{
	public bool AutoRepeat
	{
		get { return (bool)GetValue(AutoRepeatProperty); }
		set { SetValue(AutoRepeatProperty, value); }
	}

	public static readonly DependencyProperty AutoRepeatProperty =
		DependencyProperty.Register(
			"AutoRepeat", 
			typeof(bool), 
			typeof(AutoRepeatBehavior), 
			new PropertyMetadata(false, new PropertyChangedCallback(AutoRepeatChanged))
			);

	protected override bool Initialize()
	{
		AssociatedObject.Loaded += AssociatedObject_Loaded;
		return base.Initialize();
	}

	private void AssociatedObject_Loaded(object sender, RoutedEventArgs e)
	{
		AssociatedObject.MediaPlayer.IsLoopingEnabled = AutoRepeat;
		AssociatedObject.Loaded -= AssociatedObject_Loaded;
	}

	private static void AutoRepeatChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
	{
		if (d is AutoRepeatBehavior behavior
			&& behavior.AssociatedObject is MediaPlayerElement mpe
			&& mpe.MediaPlayer is Windows.Media.Playback.MediaPlayer mp)
			mp.IsLoopingEnabled = (bool)e.NewValue;
	}
}

And something similar can be done for the IsMuted property

Describe alternatives you've considered

Ideally it would be great if there was a built-in solution to access these properties, but I don't know of any alternatives at this time.

Metadata

Metadata

Assignees

No one assigned

    Labels

    feature request πŸ“¬A request for new changes to improve functionality

    Type

    No type

    Projects

    Status

    Done

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions