Wpf 如何使用非相对uri指定MediaElement.Source?

Wpf 如何使用非相对uri指定MediaElement.Source?,wpf,Wpf,我们有一些WPF模块,它们托管在cpp非托管/托管应用程序中。当为媒体内容指定相对Uri时,此环境会造成问题。例如,我可以在testapp中执行类似的操作: <MediaElement Grid.Row="0" x:Name="player" Source="media\Getting started with.wmv" LoadedBehavior="Manual" UnloadedBehavior="Stop" Stretch="Fill" MediaOp

我们有一些WPF模块,它们托管在cpp非托管/托管应用程序中。当为媒体内容指定相对Uri时,此环境会造成问题。例如,我可以在testapp中执行类似的操作:

    <MediaElement Grid.Row="0"  x:Name="player"  Source="media\Getting started with.wmv" LoadedBehavior="Manual" UnloadedBehavior="Stop" Stretch="Fill" 
        MediaOpened="Element_MediaOpened" MediaEnded="Element_MediaEnded"/>
我得到一个例外:

Cannot navigate to application resource 'pack://application:,,,/media/Getting started with.wmw' by using a WebBrowser control. For URI navigation, the resource must be at the application�s site of origin. Use the pack://siteoforigin:,,,/ prefix to avoid hard-coding the URI.
如果我尝试像这样使用“siteoforigin”模式:

Source="pack://application:,,,/media/Getting started with.wmv"
Source="pack://siteoforigin:,,,/media/Getting started with Olga 7.wmv"
        player.Source = new Uri(CreateAbsolutePathTo("media/Getting started with.wmv"), UriKind.Absolute);

    private static string CreateAbsolutePathTo(string mediaFile)
    {
        return Path.Combine(new FileInfo(Assembly.GetExecutingAssembly().Location).DirectoryName, mediaFile);
    }
我得到另一个错误:

Application identity is not set.
媒体文件设置为“内容”并带有“始终复制”

如何在Wpf桌面应用程序中使用绝对uri指定MediaElement源?

我找到了一个解决方案(有点)。我猜相对url无法解析,因为main.exe是cpp mfc应用程序。因此,为了创建绝对uri,我做了如下操作:

Source="pack://application:,,,/media/Getting started with.wmv"
Source="pack://siteoforigin:,,,/media/Getting started with Olga 7.wmv"
        player.Source = new Uri(CreateAbsolutePathTo("media/Getting started with.wmv"), UriKind.Absolute);

    private static string CreateAbsolutePathTo(string mediaFile)
    {
        return Path.Combine(new FileInfo(Assembly.GetExecutingAssembly().Location).DirectoryName, mediaFile);
    }
我绑定到一个viewmodel,因此该逻辑被包装到viewmodel上的一个属性中,并且源数据绑定在xaml中


工作正常,但没有我想要的那么漂亮。

只有你需要这样做:

        MediaElement bb = new MediaElement();
        stage.Children.Add(bb);
        bb.Source = new Uri("Recursos/MagicWandNoise.wav", UriKind.Relative);
        Debug.WriteLine("URL:" + bb.Source);
        bb.LoadedBehavior = MediaState.Manual;
        bb.Play();
然后在调试文件夹中添加二进制资源,检查此

记住,要使媒体元素正常工作,您需要添加一个可视的

        Canvas.Children.Add(bb);