WPF Style can't work on multiple controls

末鹿安然 提交于 2020-01-16 13:15:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!