【发布时间】:2021-05-02 07:00:09
【问题描述】:
我有这个转换器:
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 是
<MediaElement x:Name="media_Player"
Source="{Binding SelectedItem.Key, ElementName=lv_Medias, Converter={StaticResource MediaSourceConverter}}"
Width="322" Height="181" />
当转换器返回与 youtube 的链接时,会从主窗口代码中引发 Null 异常。该链接始终有效,并且可以从 Web api 中检索。
如果我在 MediaElement 绑定中删除转换器,则以 http* 开头的链接时媒体播放良好,当然,在其他情况下不播放但不会抛出错误。
有什么想法吗?
谢谢
【问题讨论】:
-
// This case throw Null Exception in main windows code return ("https://www.youtube.com/watch?v=" + link);如果该行抛出 NRE,我会感到惊讶。link发生时的确切值是多少? -
我也很惊讶 :(,链接值是一个 youtube id,例如:“iQJNBVW8QhI”
-
请不要说链接有效。告诉我们确切的值。
-
你能分享异常的堆栈跟踪吗?
-
我认为问题在于 MediaElement 需要一个指向媒体文件(例如 MP4 文件)的链接,而您正在给它一个 Youtube 页面。虽然 Youtube 页面上确实播放了视频,但它本身并不是视频文件。
标签: c# wpf xaml converters mediaelement