【问题标题】:MediaElement Source in codebehind代码隐藏中的 MediaElement 源
【发布时间】:2014-10-16 10:23:21
【问题描述】:

为什么这段代码会出错

wpf 代码

<MediaElement x:Name="Player" LoadedBehavior="Manual"/>

c#代码

Player.Source = new Uri(@"C:\Users\Georgi\AppData\Local\VideoPresenter\Content\1.mp4", UriKind.RelativeOrAbsolute);

产生的错误是

VideoPresenter.exe 中出现“System.NullReferenceException”类型的异常,但未在用户代码中处理

附加信息:对象引用未设置为对象的实例。

【问题讨论】:

  • 看起来 Player 为空。您必须先创建一个实例。在该行设置一些断点并对其进行调试。当它跳转到该行时,尝试将鼠标悬停在Player 上,它应该会收到null 的通知。
  • 确保您的 Player 的 c# 代码在 Player 元素初始化后执行。您的代码似乎在 InitializeComponent() 例程之前触发

标签: c# wpf mediaelement


【解决方案1】:

问题在于 InitializeCompoent() 位于构造函数的末尾。

Player.Source = new Uri(tempPath, UriKind.RelativeOrAbsolute);
Player.Play();
InitializeComponent();

InitializeComponent 应该像这样在最顶端。

InitializeComponent();
Player.Source = new Uri(tempPath, UriKind.RelativeOrAbsolute);
Player.Play();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-14
    • 2016-10-30
    • 2010-10-20
    • 1970-01-01
    • 2011-09-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多