如何在整个WPF应用程序中重用样式?

时间:2012-01-13 12:20:42

标签: .net wpf

我想在我的应用程序的几个地方使用下面的代码段(从https://stackoverflow.com/a/3675110/782880找到)。而不是在任何地方复制/粘贴,我怎么能把它放在一个地方并在各种XAML文件中引用特定的列表框(按键?)?

<ListBox....> 
    <ListBox.Resources> 
            <Style TargetType="ListBoxItem"> 
                <Setter Property="Template"> 
                    <Setter.Value> 
                        <ControlTemplate TargetType="ListBoxItem"> 
                            <Border Name="Border" Padding="2" SnapsToDevicePixels="true"> 
                                <ContentPresenter /> 
                            </Border> 
                            <ControlTemplate.Triggers> 
                                <Trigger Property="IsSelected" Value="true"> 
                                    <Setter TargetName="Border" Property="Background" 
                                            Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/> 
                                </Trigger> 
                            </ControlTemplate.Triggers> 
                        </ControlTemplate> 
                    </Setter.Value> 
                </Setter> 
        </Style> 
    </ListBox.Resources> 
</ListBox> 

1 个答案:

答案 0 :(得分:8)

您可以将其放入适当级别的Resources集合中。例如,如果您需要应用程序范围,请将其放在App.xaml

E.g。

<Application
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  StartupUri="MainWindow.xaml"
  >

 <Application.Resources>
   <Style TargetType="ListBoxItem"> 
     <Setter Property="Template"> 
       ...                      
     </Setter>
   </Style> 
 </Application.Resources>

</Application>

您可以提供资源键,然后使用适当的键设置相应的Style属性,例如用键定义你的风格:

<Style x:Key="MyStyle" TargetType="ListBoxItem">

并按键使用资源:

<ListBox x:Name="lstItems" ItemContainerStyle="{StaticResource MyStyle}">