我想在我的应用程序的几个地方使用下面的代码段(可从/sf/answers/257257731/找到).而不是在任何地方复制/粘贴,我怎么能把它放在一个地方并在各种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>
Run Code Online (Sandbox Code Playgroud)
您可以将它放在适当级别的Resources集合中.例如,如果您需要应用程序范围,请将其放在App.xaml中.
例如
<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>
Run Code Online (Sandbox Code Playgroud)
您可以提供资源键,然后使用适当的键设置相应的Style属性,例如使用键定义样式:
<Style x:Key="MyStyle" TargetType="ListBoxItem">
Run Code Online (Sandbox Code Playgroud)
并按键使用资源:
<ListBox x:Name="lstItems" ItemContainerStyle="{StaticResource MyStyle}">
Run Code Online (Sandbox Code Playgroud)