WPF UserControl Resources

resourcedictionarywpfxaml

I made a ResourceDictionary in a WPF User Control Assembly. I Want to be able to use this across this UserControl and have all the styles in this separated file.

The ResourceDictionary:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">    
    <Style x:Key="c1BtnX1">
        <Setter Property="Background" Value="Bisque"></Setter>
    </Style>    
</ResourceDictionary>

It's Address is The User Control Assembly Resources/mainResX.xaml
and the View is in the same assembly/Views/view.xaml

The usage I think could be:

<Border Style="{StaticResource ResourceKey=c1BtnX1}" 
        BorderBrush="Black"  
        Width="20" 
        Height="20">
               <TextBlock Text="X" />
</Border>

Also I tried the below code inside the UserControl, to define Per Control Resources but this way also seems it couldn't find the resources.

 <UserControl ... >
    <UserControl.Resources>
        <ResourceDictionary Source="../Resources/mainResX.xaml" />            
    </UserControl.Resources>

Where and How should I place/Define this ?

Best Answer

I can't tell what your file structure is from info provided.

If the resource.xaml and control.xaml are in the same folder of the same assembly, you would just reference mainResX.xaml without "/Resources" first; otherwise you need to account for the file structure somehow.

Are they in the same assembly? You can 'walk' the tree up with as many "../" strings prepended to the location as needed, and the in using the folders (ie, "../Resources/mainResX.xaml")

If they are in different assemblies, you need to specify a pack uri. You can actually always do this, although it is a little cumbersome when not necessary. Here is an example

<ResourceDictionary Source="pack://application:,,,/MyAssembly.Wpf;component/Resources/mainResX.xaml" />

HTH,
Berryl

Related Topic