Search code examples
windows-phone-7xamlstaticresourceconverters

Can I use subobjects of a StaticResource?


Feeling a bit bored of cut and pasting converters between projects at the moment.

Is there any way I can use a single Converters object which has converters as fields/properties?

e.g. something like:

<Application.Resources>
    <sharedLib:Converters
        x:Key="Converters" />
</Application.Resources>

<TextBlock Text="{Binding Target, Converter={StaticResource Converters.MakeAllCaps}}" />

If not, then does anyone have any suggestions for how the converters might otherwise be bulk imported?


Solution

  • You can define all your converters in a resource dictionary like this:

    <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                        xmlns:loc="...">
    
        <loc:BooleanToVisibilityConverter x:Key="BooleanToVisibility" />
        <loc:MakeAllCapsConverter x:Key="MakeAllCaps" />
    
        <!-- Define all the common converters here -->
    </ResourceDictionary>
    

    Now you can import this resource dictionary anywhere via MergedDictionaries like this:

    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Converters.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
    
    <TextBlock Text="{Binding Target, Converter={StaticResource MakeAllCaps}}" />