How can you reuse the style throughout your WPF application?

I would like to use the snippet below (found at https://stackoverflow.com/questions/61839/... ) in several places of my application. Instead of copying / pasting everywhere, how can I put this in one place and reference it for specific lists (by key?) In different 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> 
+4
source share
1 answer

You can place it in the resource collection at the appropriate level. For example, if you want an application area, put it in App.xaml .

eg.

 <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 specify your resource keys, and then set the corresponding style property using the corresponding key, for example. define your style with the key:

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

and use the resource by key:

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

Source: https://habr.com/ru/post/1390823/


All Articles