WPF样式不能在多个控件上使用 [英] WPF Style can't work on multiple controls

查看:191
本文介绍了WPF样式不能在多个控件上使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在控件上使用wpf样式,以便可以一次在多个控件上使用样式.通常可以.例如,我做了一个saveButtonStyle,并将其应用于应用程序中的每个保存按钮.但这不适用于MenuItems. 我为菜单项创建了样式,该样式在项目旁边包含一个图标. 这是它的一个屏幕截图.

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.

您会看到Datagrid有一个ContextMenu,并且其中有多个菜单项.在这种情况下,请注意设置警报.它有一个图标. 设置警报菜单"项也位于该菜单项旁边的另一个菜单数据网格中.当我点击那个 它也出现了

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

这是我的风格

  <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?

推荐答案

样式menuItemAlert仅创建Image的一个实例,并且只能在一个位置显示它.为了克服这个问题,请为该Image创建一个单独的非共享资源.

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>

这篇关于WPF样式不能在多个控件上使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆