In WPF: Is there a way to combine two styles for one control?

My situation is similar to the following.

I have an App.xaml that includes Style for a ListView, like this:

<Style x:Key="{x:Type ListViewItem}" TargetType="ListViewItem"> <Setter Property="SnapsToDevicePixels" Value="true"/> <Setter Property="OverridesDefaultStyle" Value="true"/> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="ListBoxItem"> ... 

However, I want to add some styles to another xaml, say in Window.xaml, like this:

  <ListView AlternationCount="2" Background="#FFECECEC"> <ListView.Resources> <Style x:Key="{x:Type ListViewItem}" TargetType="{x:Type ListViewItem}"> <EventSetter Event="PreviewMouseDoubleClick" Handler="OnPreviewMouseDoubleClick" /> </Style> </ListView.Resources> </ListView> 

So what I want to do is define the base design style in App.xaml as the default style. Then add some changes, such as adding a context menu, adding events from each xaml.

But, with the above implementation, the style defined in App.xaml will be overwritten with the style defined in Window.xaml.

Is there a way to solve the problem and achieve it?

+6
source share
2 answers

Styles have the BasedOn property:

 <Style x:Key="Style1"> ... </Style> <Style x:Key="Style2" BasedOn="{StaticResource Style1}"> ... </Style> 

Btw: <Style x:Key="{x:Type ListViewItem}" seems a little strange. x:Key must be a unique key in the xaml dictionary - usually a string.

+9
source

If the BasedOn attribute meets your needs, this is the best choice. However, for more complex scenarios, for example, the solution mentioned in this question is more flexible.

+2
source

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


All Articles