Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
328 views
in Technique[技术] by (71.8m points)

c# - 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

question from:https://stackoverflow.com/questions/65936157/wpf-mediaelement-source-defined-by-converter-throw-nullexception

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...