Search code examples
c#wpfxamlconvertersmediaelement

WPF MediaElement source defined by converter throw NullException


I have this converter :

    public class MediaSourceConverter : DependencyObject, IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value == null || value.ToString().Trim() == "" || value.ToString() == "0")
        {
            // This case is running well
            return null;
        }
        else
        {
            string link = value.ToString();
            if (link.StartsWith("plugin://plugin.video.youtube/?action=play_video&videoid="))
            {
                // This case throw Null Exception in main windows code
                return ("https://www.youtube.com/watch?v=" + link.Substring(link.LastIndexOf('=') + 1));
            }
            else if (link.StartsWith("http://") || link.StartsWith("https://"))
            {
                // This case is running well
                return link;
            }
            else
            {
                // This case throw Null Exception in main windows code
                return ("https://www.youtube.com/watch?v=" + link);
            }
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

XAML is

<MediaElement x:Name="media_Player" 
              Source="{Binding SelectedItem.Key, ElementName=lv_Medias, Converter={StaticResource MediaSourceConverter}}"
              Width="322" Height="181" />

When the converter return a link with youtube, a Null exception is thrown from the main window code. The link is always valid and is retrieved from a web api.

If I remove the converter in the MediaElement binding, the media is playing well when link starting with http*, and, of course, not playing in the other cases but no error is thrown.

Any ideas ?

Thanks


Solution

  • The problem is that the MediaElement is expecting a link to a media file (MP4 file for example) and you're giving it a Youtube page. Whilst the Youtube page does have a video playing on it, it is not a video file in itself