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.
<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>
You can give your resources keys, and then set the appropriate Style property using the appropriate key, e.g. define your style with key:
<Style x:Key="MyStyle" TargetType="ListBoxItem">
and use the resource by key:
<ListBox x:Name="lstItems" ItemContainerStyle="{StaticResource MyStyle}">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With