Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you reuse a style throughout a WPF application?

Tags:

.net

wpf

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> 
like image 291
WhiskerBiscuit Avatar asked Jan 17 '23 19:01

WhiskerBiscuit


1 Answers

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}">
like image 146
devdigital Avatar answered Jan 21 '23 12:01

devdigital