c#wpf MediaElement black flash

时间:2018-05-08 17:56:32

标签: c# wpf

当MediaElement开始播放视频时,它会像黑框一样显示。这是代码:

<Window x:Class="MediaElementTest.MainWindow" /* */
        Title="MainWindow" Height="350" Width="525" Background="Red">
    <Grid>
        <ContentControl x:Name="contentControl"/>
    </Grid>
</Window> 

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        NextState();
    }

    public void NextState()
    {
        var content = new VideoState();
        contentControl.Content = content;
    }
}

<UserControl x:Class="MediaElementTest.VideoState" /* */
             d:DesignHeight="300" d:DesignWidth="300">
    <Grid>
        <MediaElement x:Name="videoPlayer" MediaEnded="videoPlayer_MediaEnded" LoadedBehavior="Manual" />
    </Grid>
</UserControl>

public partial class VideoState : UserControl
{
    public VideoState()
    {
        InitializeComponent();
        videoPlayer.Source = new Uri("C:\\wpf\\bin\\Debug\\data\\start.mp4");
        //videoPlayer.Position = TimeSpan.FromMilliseconds(100); //!!! WORKS FINE WITH IT
        videoPlayer.Play();
    }

    private void videoPlayer_MediaEnded(object sender, RoutedEventArgs e)
    {
        videoPlayer.Source = null;
        videoPlayer = null;
        GC.Collect();

        MainWindow wnd = (MainWindow)Application.Current.MainWindow;
        wnd.NextState();
    }
}

如果我将videoPlayer.Position设置为100毫秒,它可以正常工作。我怎样才能摆脱这个黑框。我试图设置ScrubbingEnabled="true"并执行以下操作:

videoPlayer.Play();
videoPlayer.Pause();
videoPlayer.Play();

但是没有区别,仍然会出现黑色弹出窗口。如果我在mediaEnded事件中将videoPlayer.Position设置为0ms并播放它也可以。我将不胜感激任何帮助。

1 个答案:

答案 0 :(得分:0)

获取用户控件的Loaded事件,并在用户控件的代码隐藏文件中的Loaded事件处理程序中移动以下代码

videoPlayer.Source = new Uri("C:\\wpf\\bin\\Debug\\data\\start.mp4");
videoPlayer.Play();

将VideoState用户控件正确加载为窗口内容后,才会执行更多逻辑来播放视频。我希望它能解决黑屏问题。