Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In WPF, Is there any way to combine two Style for one control?

Tags:

styles

wpf

xaml

My situation is like following.

I have a App.xaml which includes Style for 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 wanna add some styles into another xaml, let's 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 style for base design in App.xaml as Default style. Then, add some modify such as adding a context menu, adding events from each xaml.

But, with above implementation, Style defined in App.xaml will be overwrote by Style defined in Window.xaml.

Is there any way to solve the issue and achieve it?

like image 754
Aki24x Avatar asked Jun 11 '11 00:06

Aki24x


2 Answers

Styles have a BasedOn property:

<Style x:Key="Style1">
...
</Style>

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

Btw: <Style x:Key="{x:Type ListViewItem}" seems a bit weird. The x:Key should be a unique key in a xaml dictionary - usually a string.

like image 90
ChrisWue Avatar answered Nov 14 '22 23:11

ChrisWue


If the BasedOn attribute fits your needs, it's the best choice. For more complicated scenarios though, something like the solution referred to in this question is more flexible.

like image 32
skst Avatar answered Nov 14 '22 23:11

skst