Resource resolution from one UserControl to the parent UserControl

I have a UserControl1 user element that defines a style in its resources. This user control contains an instance of UserControl2 that references this style:

<UserControl x:Class="UserControl1"> <UserControl.Resources> <Style x:Key="MyStyle" /> </UserControl.Resources> <Grid> <UserControl2 /> </Grid> </UserControl> <UserControl x:Class="UserControl2"> <Grid Style="{StaticResource MyStyle}"> </Grid> </UserControl> 

However, UserControl2 cannot find this style resource, even if it is in the logical tree (within the resources of UserControl1). How can I get UserControl2 to search for resources in UserControl1?

+4
source share
2 answers

You can do this, but I would suggest using a ResourceDictionary .

Anyway, if you want to do it this way, you can use FindAncestor to find the parent and access the Resource from the parent ResourceDictionary

 <UserControl x:Class="UserControl1"> <UserControl.Resources> <Style x:Key="MyStyle" /> </UserControl.Resources> <Grid> <UserControl2 /> </Grid> </UserControl> <UserControl x:Class="UserControl2"> <Grid Style="{Binding Resources[MyStyle], RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:UserControl1}}}"> </Grid> </UserControl> 

Beacause Resource is a dictionary that you can access using key , as in the code for

+1
source

I had the same problem, and I was able to solve it by specifying the resource through DynamicResource instead of StaticResource :

 <UserControl x:Class="UserControl2"> <Grid Style="{DynamicResource MyStyle}"> </Grid> </UserControl> 

The compiler still warns that the resource cannot be resolved.

+1
source

All Articles