Search code examples
c#xamluwpmedia-player

How to show video title in UWP MediaPlayerElement?


I am wondering how to show video title on top part of the screen with media transport controls. I'm using MediaPlayerElement in UWP, target version 14393.


Solution

  • MediaTransportControls do not provide a Title property to show video title. However, we can implement this easily as refer to Create custom transport controls.

    Since we want to add a function to the control, we need to create a new class that derives from MediaTransportControls. For a detailed tutorial, please see Create a derived control under Customize the transport controls. And for a complete sample, please refer to Media Transport Controls sample.

    Here, as you want the title shows on top part of the screen and only shows when media transport control pops up, you can add the TextBlock under the Border named "ControlPanel_ControlPanelVisibilityStates_Border" and set its VerticalAlignment to Top like the following:

    <Border x:Name="ControlPanel_ControlPanelVisibilityStates_Border">
        <Grid>
            <TextBlock VerticalAlignment="Top" Foreground="Red" FontSize="36" Text="{TemplateBinding Title}" />
            <Grid x:Name="ControlPanelGrid" ...>
        </Grid>
    </Border> 
    

    And in the code-behind, you can implement a dependency property for the setting of the title.

    public sealed class CustomMediaTransportControls : MediaTransportControls
    {
        public string Title
        {
            get { return (string)GetValue(TitleProperty); }
            set { SetValue(TitleProperty, value); }
        }
    
        // Using a DependencyProperty as the backing store for Title.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty TitleProperty =
            DependencyProperty.Register("Title", typeof(string), typeof(CustomMediaTransportControls), new PropertyMetadata(null));
    
        public CustomMediaTransportControls()
        {
            this.DefaultStyleKey = typeof(CustomMediaTransportControls);
        }
        ...
    }
    

    After this, you should be able to use your custom transport controls like:

    <MediaPlayerElement Name="MainMPE" AreTransportControlsEnabled="True" Source="video.mp4">
        <MediaPlayerElement.TransportControls>
            <local:CustomMediaTransportControls x:Name="customMTC"
                                                Title="This is a title">
            </local:CustomMediaTransportControls>
        </MediaPlayerElement.TransportControls>
    </MediaPlayerElement>