Registering a custom URI protocol to handle custom

2019-06-21 21:33发布

问题:

I'm working on a project where loose bits of XAML (and some associated IronPython code) will be dynamically loaded and executed by a client application. The client will be using a custom WCF service (and some local caching) to retrieve the XAML, backing scripts, and related resources (icons, images, etc..).

I would like to register a custom URI protocol/scheme to make it easier for the developers of the dynamic packages to reference their resources, like the following:

<UserControl xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <UserControl.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>

                <ResourceDictionary Source="custom://MyPackage/Icons.xaml"  />
                <ResourceDictionary Source="custom://MyPackage/Styles.xaml" />
                <!--                        ^^^^^^                         -->

            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </UserControl.Resources>
</UserControl>

As far as I can tell, I can derive a custom UriParser and register it, but that only seems to be half the battle. The remaining work is to provide whatever component is necessary to resolve the custom URI and retrieve the required content.

Is it possible to provide or override functionality in WPF to allow it to call my custom data service when one of my custom URIs is encountered? Or, if this is impossible, is there any sort of alternative?

回答1:

From what I understand, you need to create a class that derives from WebRequest and register it with WebRequest.RegisterPrefix.



回答2:

As an alternative, I wonder if you could create a new class that inherits from ResourceDictionary (since it is not sealed) and provide a new definition for Source. This would let you intercept the value being set to Source then and run it against your custom UriParser. This would also allow you to easily update the ResourceDictionary with the results.