问题
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.
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
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
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?
回答1:
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>
来源:https://stackoverflow.com/questions/46090738/wpf-style-cant-work-on-multiple-controls