Pacman
Pacman

Reputation: 2245

Setting MenuItem icon through style setter

<Style x:Key="ContextMenuItemStyle" TargetType="{x:Type MenuItem}">
    <Setter Property="Icon" Value="{Binding Icon}" />
    <Setter Property="Header" Value="{Binding Text}" />
    <Setter Property="ItemsSource" Value="{Binding Children}" />
    <Setter Property="Command" Value="{Binding Command}" />
</Style>

setting it in code like this:

Uri refreshUri = new Uri("..\\Resources\\Refresh16.bmp",UriKind.Relative);
BitmapImage refreshIcon = new BitmapImage();
refreshIcon.UriSource = refreshUri;

the Icon doesn't show up, any clues ?

Upvotes: 5

Views: 10193

Answers (2)

Jonathan
Jonathan

Reputation: 15462

For anyone still looking for a solution, this worked for me:

<Window.Resources>
    <Image x:Key="Icon" Source="/ProjectName;component/Images/IconName.ico" x:Shared="false"/>
    <Style x:Key="MenuItem">
        <Setter Property="MenuItem.Header" Value="Header Text"/>
        <Setter Property="MenuItem.Icon" Value="{DynamicResource Icon}"/>
    </Style>
</Window.Resources>

Upvotes: 7

Sheridan
Sheridan

Reputation: 69985

If the refreshIcon is the source of your Icon property, then you may need to either call NotifyPropertyChanged("Icon") after your code example (and implement the INotifyPropertyChanged interface) and/or declare Icon as a DependencyProperty.

Here is a link to more information about the INotifyPropertyChanged interface.

Ahh, I see your problem... try setting the Icon property to an Image and bind to the source of the Image:

<Setter Property="Icon">
    <Setter.Value>
        <Image Source="{Binding Icon}" />
    </Setter.Value>
</Setter>

You can also just put the image into an Images folder in your main project and reference it in xaml like this:

<Setter Property="Icon">
    <Setter.Value>
        <Image Source="/ProjectName;component/Images/IconName.ico" />
    </Setter.Value>
</Setter>

Upvotes: 8

Related Questions