March 31, 2011

Using Xaml resources in a common assembly

First put the resources in a resource dictioanry xaml file that goes into the shared resource assembly. In this sample the assembly is called Common and the common resources are placed in a subdirectory WPF of this assembly. Their is no ".cs" file associated with this Xaml file. Here is the Xaml file in the "Common" assembly with a shared listbox style called "MyListStyle":
<ResourceDictionary 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 xmlns:System="clr-namespace:System;assembly=mscorlib">
            <Style x:Key="MyListStyle" TargetType="ListBox">
   ...
            </Style>
</ResourceDictionary>

To reference these resources in another WPF component, do it from the Resources area of the WPF component. For example
<Window ... >
    <Window.Resources>
         <ResourceDictionary Source="/Common;component/WPF/Resources.xaml" />
    </Window.Resources>
 ...
        <ListBox ... Style="{StaticResource MyListStyle}" />
 ...
</Window>

To reference those resources from a WPF Application:
<Application ... >
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="/Common;component/WPF/Resources.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>

Once added to an application's resources they can be accessed anywhere in the normal fashion:
<Window ... >
...
        <ListBox ... Style="{StaticResource MyListStyle}"  />
...  
</Window>

No comments: