Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting MenuItem icon through style setter

Tags:

menuitem

wpf

xaml

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

like image 562
Pacman Avatar asked Mar 03 '11 23:03

Pacman


2 Answers

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>
like image 101
Sheridan Avatar answered Nov 17 '22 09:11

Sheridan


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>
like image 35
Jonathan Avatar answered Nov 17 '22 08:11

Jonathan