Saeed Asgari
Saeed Asgari

Reputation: 427

WPF Style can't work on multiple controls

I am using wpf style on my controls so that i can use an style on multiple controls at once. It usually works. for example i made an saveButtonStyle and i apply it on every save button on my application. But it doesn't work on MenuItems. I made a style for my menuitems which contains an icon next to the items. This is one screen shot of it. enter image description here

You see the Datagrid has an ContextMenu and within it there is multiple menu items. in this case pay attention to Set Alarm. it has an icon. This Set Alarm Menu item is also in another menu datagrid next to this one. When i click that one it appears too enter image description here

But problem is when i right click back to the other datagrid the icon is gone and wont come back. this is the screen shot enter image description here

Here is the style I made

  <Style x:Key="menuItemAlert" TargetType="{x:Type MenuItem}">
            <Setter Property="Icon">
                <Setter.Value>
                    <Image Source="Content/AlertIcon.png" Width="20" Height="20" />
                </Setter.Value>
            </Setter>
        </Style>

And here is how I apply it to my controls

<MenuItem x:Name="customerContextMenuSetAlarm" Header="SetAlarm"  Style="{StaticResource menuItemAlert}" Click="customerContextMenuSetAlarm_Click"/>

Do you know why it happens?

Upvotes: 0

Views: 372

Answers (1)

ASh
ASh

Reputation: 35646

style menuItemAlert creates only one instance of Image and can display it in one place only. to overcome this make a separate non-shared resource for that Image.

<Image x:Key="AlertIcon" x:Shared="False" Source="Content/AlertIcon.png" Width="20" Height="20" />

<Style x:Key="menuItemAlert" TargetType="{x:Type MenuItem}">
    <Setter Property="Icon" Value="{StaticResource AlertIcon}"/>
</Style>

Upvotes: 2

Related Questions