Search code examples
wpfwpf-style

Exception on nested style wpf


This is my style inside Grid.Resources

<ControlTemplate x:Key="ToggleButtonControlTemplate" TargetType="{x:Type ToggleButton}"
    <Grid>
         .....
    </Grid>
    <ControlTemplate.Triggers>
         .....
    </ControlTemplate.Triggers>
</ControlTemplate>

<Style TargetType="ToggleButton" x:Key="ToggleButtonStyle">
    <Setter Property="FontSize" ....... />
    .....
    <Setter Property="Template" Value="{StaticResource ToggleButtonControlTemplate}" />
</Style>

<Style x:Key="SidePanel" TargetType="StackPanel">
    <Style.Resources>
        <StaticResource ResourceKey="PreviewSidePanelToggleButtonStyle" /> ---> Exception
    </Style.Resources>
</Style>

With this design but UI looks good in design mode. But when I run this application I get an exception in the line:

<StaticResource ResourceKey="PreviewSidePanelToggleButtonStyle" />

with the message: "Set property 'System.Windows.Style.Resources' threw an exception".

Any idea what went wrong?


Solution

  • The Exception is because you are trying to assign Style to Resources . Resource property is of Type ResourceDictionary and your is of type Style so casting is not possible and Exception is thrown .I dont know why you doing this but why so ever you doing this it is incorrect you can access the PreviewSidePanelToggleButtonStyle directly instead of forwarding it to Style resources. Read remark section