Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF UserControl Style -- How do I set the style from the parent if the control is in an external assembly?

Basically I have the following structure:

<Window ...
        xmlns:my="http://schemas.company.com/WPF/Controls"
        >
    <Window.Resources>
        <Style x:Key="MyStyle1" TargetType={x:Type TextBlock}>
            ...
        </Style>
    </Window.Resources>
    <Grid x:Name="LayoutRoot">
        <my:MyUserControl1 />
        <my:MyUserControl1 />
        <my:MyUserControl2 />
        <my:MyUserControl2 />
    </Grid>
</Window>

<UserControl ...
             >
    <TextBlock Style={ ?? What Goes Here ??} />
</UserControl>


How do I apply the style declared in the Window resources so that it goes to the UserControl that is being pulled from an external assembly?
like image 783
michael Avatar asked Mar 10 '11 17:03

michael


1 Answers

If you want the Style to be applied to all TextBlocks, including the ones in MyUserControl, just leave the x:Key out and it will be applied implictly

<Style TargetType="{x:Type TextBlock}">
    <Setter Property="Foreground" Value="Green"/>
</Style>

If you want it to be set explicitly you can use DynamicResource in the UserControls

<Window.Resources>
    <Style x:Key="MyStyle1" TargetType="{x:Type TextBlock}">
        <Setter Property="Foreground" Value="Green"/>
    </Style>
</Window.Resources>
<StackPanel>
    <my:UserControl1 />
    <my:UserControl1 />
    <my:UserControl1 />
    <my:UserControl1 />
</StackPanel>

<UserControl ...>
    <TextBlock Style="{DynamicResource MyStyle1}" Text="TextBlock"/>
</UserControl>
like image 53
Fredrik Hedblad Avatar answered Sep 28 '22 13:09

Fredrik Hedblad