Sanjay Cruze Sanjay Cruze - 29 days ago 13
C# Question

WPF Styling nested elements from a style

Similar to this SO question, I am trying to style ComboBoxItems as easily as possible. However, I am making a custom style based on ComboBox's default style found here.

<Style x:Key="MultiComboBox" TargetType="{x:Type ComboBox}">
<Style.Resources>
<Style TargetType="{x:Type ComboBoxItem}">
<Setter Property="Style" Value="{StaticResource MultiComboBoxItem}"/>
</Style>
</Style.Resources>

<Setter Property="SnapsToDevicePixels" Value="true" />
<!--<Setter Property="OverridesDefaultStyle" Value="true" />-->
<Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Auto" />
<Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Auto" />
...
...
</Style>
.
.
.
<ComboBox Style="{StaticResource MyComboBox}">
<ComboBoxItem x:Name="First">First</ComboBoxItem>
<ComboBoxItem x:Name="Second">Second</ComboBoxItem>
<ComboBoxItem x:Name="Third">Third</ComboBoxItem>
</ComboBox>


I added the
<Style.Resources>
bit to the top in hopes to only need one reference here, instead of individually adding it to nested elements, or even needing to add it to the element in the first place. Also, I commented out all of the
OverridesDefaultStyle
Setters.

However, then I get a XAMLparseexception, "Style object is not allowed to affect the Style property of the object to which it applies". The error makes sense by itself, but I thought since I was targeting
ComboBoxItem
's it should work. Is there a way around this?

ASh ASh
Answer

Style object is not allowed to affect the Style property of the object to which it applies

the problematic lines are these:

<Style TargetType="{x:Type ComboBoxItem}">
    <Setter Property="Style" Value="{StaticResource MultiComboBoxItem}"/>
</Style>

try rewrite them as

<Style TargetType="{x:Type ComboBoxItem}" BasedOn="{StaticResource MultiComboBoxItem}">
</Style>

or maybe better use ItemContainerStyle property:

<Style x:Key="MultiComboBox" TargetType="{x:Type ComboBox}">

    <Setter Property="ItemContainerStyle" Value="{StaticResource MultiComboBoxItem}" />
    <Setter Property="SnapsToDevicePixels" Value="true" />
    <!--<Setter Property="OverridesDefaultStyle" Value="true" />-->
    <Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Auto" />
    <Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Auto" />

</Style>