LastBye
LastBye

Reputation: 1173

WPF UserControl Resources

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 ?

Upvotes: 1

Views: 13989

Answers (2)

Joe
Joe

Reputation: 2564

Personally I like to use my App.xaml to specify a "MergedDirectory" of XAML files containing styles that I use globally in my app. I usually have a "DefaultStyles.xaml" to set any global style (like when you want all textboxes in the app to look the same without specifying a style). Then I have a "Styles.xaml" to set specific styles, or you could even have one xaml per control type if you really have a bunch of them...

The fact that you place these under app.xaml makes them global to your app and don't require you to constantly re-specify the paths and dictionaries. Of course this may not fit all coding situations, but for me it's a time saver.

Upvotes: 2

Berryl
Berryl

Reputation: 12833

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

Upvotes: 4

Related Questions