如何从外部为 ItemsPanel 设置样式?
How to set style for ItemsPanel from outside?
我定义了一个样式让所有StackPanel
变成绿色:
<Window.Resources>
<Style TargetType="StackPanel">
<Setter Property="Background" Value="Green" />
</Style>
</Window.Resources>
但是如果我使用 StackPanel
作为面板模板,那么它就不是绿色的:
<UniformGrid>
<StackPanel /><!-- this one is green -->
<ItemsControl>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel /><!-- this one is not -->
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</UniformGrid>
为什么?如何让它也变绿?
将隐式 Style
移动到 App.xaml
或将基于隐式 Style
的资源添加到 ItemsPanelTemplate
:
<ItemsControl>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<ItemsPanelTemplate.Resources>
<Style TargetType="StackPanel" BasedOn="{StaticResource {x:Type StackPanel}}" />
</ItemsPanelTemplate.Resources>
<StackPanel />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
如果您不执行任何操作,则不从 Control
继承的类型将不会采用隐式样式。
我定义了一个样式让所有StackPanel
变成绿色:
<Window.Resources>
<Style TargetType="StackPanel">
<Setter Property="Background" Value="Green" />
</Style>
</Window.Resources>
但是如果我使用 StackPanel
作为面板模板,那么它就不是绿色的:
<UniformGrid>
<StackPanel /><!-- this one is green -->
<ItemsControl>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel /><!-- this one is not -->
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</UniformGrid>
为什么?如何让它也变绿?
将隐式 Style
移动到 App.xaml
或将基于隐式 Style
的资源添加到 ItemsPanelTemplate
:
<ItemsControl>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<ItemsPanelTemplate.Resources>
<Style TargetType="StackPanel" BasedOn="{StaticResource {x:Type StackPanel}}" />
</ItemsPanelTemplate.Resources>
<StackPanel />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
如果您不执行任何操作,则不从 Control
继承的类型将不会采用隐式样式。