I’d like to use the snippet below (found from https://stackoverflow.com/a/3675110/782880) in several places in my application. Instead of copy/pasting everywhere, how can I put this in one place and reference it for specific listboxes (by key?) in various XAML files?
<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>
You can place it into a Resources collection at the appropriate level. For example, if you want application scope, then place it in App.xaml.
E.g.
You can give your resources keys, and then set the appropriate Style property using the appropriate key, e.g. define your style with key:
and use the resource by key: