WPF: address of nested styles by key
I have a fairly complex WPF custom control that requires a lot of custom styles and a few different styles for the same control types. These same styles are not used elsewhere.
I would like to use nested styles (using Style.Resources
) as a kind of namespaced mechanism:
User control example:
<UserControl Style="{StaticResource AwesomeControl}>
<Grid>
<Button Style="{StaticResource ButtonA}"/>
<Button Style="{StaticResource ButtonB}"/>
</Grid>
</UserControl>
How I want to define my styles:
<ResourceDictionary>
<Style TargetType="UserControl" x:Key="AwesomeControl">
<Style.Resources>
<Style TargetType="Button" x:Key="ButtonA"> </Style>
<Style TargetType="Button" x:Key="ButtonB"> </Style>
</Style.Resources>
</Style>
</ResourceDictionary>
However, this doesn't work. From what I can tell, it is not possible to treat nested styles by their key. (I've searched a lot, but can't find a single example doing something like this.)
I can get it to work easily by removing the nesting of the styles, keeping them all at the top level. However, then I have to change their keys to something like AwesomeControlButtonA
etc. to distinguish them from other parts of the application.
It doesn't strike me as perfect.
So my question is:
Am I trying somehow with the code above? If not, are there other namespaced ways I can use to prevent awkward keys like AwesomeControlButtonA?
source to share
Maybe it DynamicResource
can solve your problem
<Grid>
<Button Style="{DynamicResource ButtonA}"/>
<Button Style="{DynamicResource ButtonB}"/>
</Grid>
After downvote:
<Grid>
<Grid.Resources>
<Style x:Key="AW" TargetType="UserControl">
<Style.Resources>
<Style TargetType="Button" x:Key="AB">
<Setter Property="Background" Value="Red" />
</Style>
<Style TargetType="Button" x:Key="BB">
<Setter Property="Background" Value="Yellow" />
</Style>
</Style.Resources>
</Style>
<Style x:Key="AR" TargetType="UserControl">
<Style.Resources>
<Style TargetType="Button" x:Key="AB">
<Setter Property="Background" Value="Green" />
</Style>
<Style TargetType="Button" x:Key="BB">
<Setter Property="Background" Value="Blue" />
</Style>
</Style.Resources>
</Style>
</Grid.Resources>
<StackPanel>
<UserControl Style="{StaticResource AW}">
<StackPanel>
<Button Content="A" Style="{DynamicResource AB}" />
<Button Content="A" Style="{DynamicResource BB}" />
</StackPanel>
</UserControl>
<UserControl Style="{StaticResource AR}">
<StackPanel>
<Button Content="A" Style="{DynamicResource AB}" />
<Button Content="A" Style="{DynamicResource BB}" />
</StackPanel>
</UserControl>
</StackPanel>
</Grid>
I think this is the solution .. and thanks for voting. The critic is always better :)
source to share