与这个Stack Overflow问题类似,我正在尝试尽可能轻松地为ComboBoxItems设置样式。但是,我正在基于ComboBox的默认样式制作自定义样式,可以在这里找到。
<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>
我在顶部添加了
<Style.Resources>
,希望只需一个引用即可,而不是分别将其添加到嵌套元素中,或者甚至需要在首次添加元素时添加它。此外,我注释掉了所有的OverridesDefaultStyle
Setters。
然而,接着我得到了一个XAMLparseexception错误,"Style object is not allowed to affect the Style property of the object to which it applies"。这个错误本身很有道理,但我认为既然我正在针对ComboBoxItem
,它应该可以工作。有没有什么办法可以解决这个问题?
ItemContainerStyle
的处理方式让我觉得那不是适合我的正确答案。感谢您纠正我。一旦SO允许,我会接受这个答案。 - user6732861ItemContainerStyle
属性。不过我最终想出了解决方法。在stackpanel样式中,我添加了<Style.Resources> <Style BasedOn="{StaticResource MyRadioButton}" TargetType="{x:Type RadioButton}"/> </Style.Resources>
。 - user6732861