<Style TargetType="{x:Type local:DrawerMenu}">
<Setter Property="ItemContainerStyle" Value="{StaticResource LBXI.DrawerMenu}"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:DrawerMenu}">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition/>
</Grid.RowDefinitions>
<ToggleButton Content="Open" x:Name="Icon" IsChecked="{Binding RelativeSource={RelativeSource Templatedparent}, Path=IsOpen,Mode=TwoWay}" HorizontalAlignment="Left" Width="30" Height="30"/>
<ItemsPresenter Grid.Row="1"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style TargetType="{x:Type ListBoxItem}" x:Key="LBXI.DrawerMenu">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListBoxItem}">
<Border BorderThickness="1" BorderBrush="Black" >
<TextBox Text="{Binding .}"/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
I have a control that inherits from ListBox and it has an ItemContainerStyle property and I’m using a static resource and when I load it with StaticResource I get an InvalidCastException: Unable to cast object of type ‘MS.Internal.NamedObject’ to type ‘System.Windows.Style’.
Loading with DynamicResource is no problem.
I suspect that it is a resource loading problem, that is, the resource is not immediately loaded into memory when the resource dictionary is loaded, but the control is created to add the resource to the resource dictionary, but I am not sure
In this case, the order of resource declaration must be observed. StaticResource is resolved at the moment of creation of the resource that uses it, and the resource that it requires must already be created at that moment. DynamicResource is resolved dynamically throughout the entire life of the resource. Therefore, it can use a resource declared later.
<Style TargetType="{x:Type ListBoxItem}" x:Key="LBXI.DrawerMenu">
<!-- XAML Body -->
</Style>
<Style TargetType="{x:Type local:DrawerMenu}">
<Setter Property="ItemContainerStyle" Value="{StaticResource LBXI.DrawerMenu}"/>
<!-- Other XAML -->
</Style>
1