ContextMenu Icons not displaying

I have some images that I use as icons for ContextMenu Items:

<UserControl.Resources>
    <Image x:Key="DeleteIco" Source="pack://application:,,,/MyProject.myControl;component/Resources/Delete.ico" Width="16" Height="16"/>
    ...
    <ContextMenu x:Key="MyMenu1">
        <MenuItem Header="Delete" Icon="{StaticResource DeleteIco}"/>
    </ContextMenu>

    <ContextMenu x:Key="MyMenu2">
        <MenuItem Header="Delete me" Icon="{StaticResource DeleteIco}"/>
    </ContextMenu>
<UserControl.Resources>

Sometimes the first menu miss the icon, sometimes the second... why? I don't do anything on the icons in the code.

Answers


You have created an Image control, and tried to put it twice in the visual tree. Since all controls can only have one parent your Image got disconnected. Thus using it a second time, the first will be disconnected, resulting in your missing icon.

You can resolve this, by not adding the Image, but the ImageSource instead to your resources:

<BitmapImage x:Key="DeleteIco" UriSource="pack://application:,,,/MyProject.myControl;component/Resources/Delete.ico" />

Your menu has to change a bit for it to work though:

<ContextMenu x:Key="MyMenu1">
    <MenuItem Header="Delete">
         <MenuItem.Icon>
              <Image Source="{StaticResource DeleteIco}" Width="16" Height="16"/>
         </MenuItem.Icon>
    </MenuItem>
</ContextMenu>

<ContextMenu x:Key="MyMenu2">
    <MenuItem Header="Delete me">
         <MenuItem.Icon>
              <Image Source="{StaticResource DeleteIco}" Width="16" Height="16"/>
         </MenuItem.Icon>
    </MenuItem>
</ContextMenu>

Update:

You can also use styles to set some basic properties of the Image for you

<Style TargetType="Image">
    <Setter Property="Width" Value="16"/>
    <Setter Property="Width" Value="16"/>
</Style>

Or use a Style for MenuItem to set the Icon each time.

<Style TargetType="MenuItem" x:Key="DeleteMenuIcon">
    <Setter Property="Icon">
        <Setter.Value>
             <Image Source="{StaticResource DeleteIco}" Width="16" Height="16"/>
        </Setter.Value>
    </Setter>
</Style>

And the MenuItem:

<MenuItem Header="Delete me" Style="{StaticResource DeleteMenuIcon}" />

Need Your Help

Do HTML doctypes guarantee formal parsing?

html browser html-parsing

Do HTML doctypes guarantee formal parsing?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.