通过样式设置器设置MenuItem图标

Pac*_*man 5 wpf xaml menuitem

<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>
Run Code Online (Sandbox Code Playgroud)

在这样的代码中设置它:

Uri refreshUri = new Uri("..\\Resources\\Refresh16.bmp",UriKind.Relative);
BitmapImage refreshIcon = new BitmapImage();
refreshIcon.UriSource = refreshUri;
Run Code Online (Sandbox Code Playgroud)

图标没有出现,任何线索?

She*_*dan 7

如果它refreshIcon是您的Icon属性的源,那么您可能需要NotifyPropertyChanged("Icon")在代码示例之后调用(并实现INotifyPropertyChanged接口)和/或声明Icon为a DependencyProperty.

以下是有关该INotifyPropertyChanged界面的更多信息的链接.

啊,我看到你的问题...尝试将Icon属性设置为an Image并绑定到以下的源Image:

<Setter Property="Icon">
    <Setter.Value>
        <Image Source="{Binding Icon}" />
    </Setter.Value>
</Setter>
Run Code Online (Sandbox Code Playgroud)

您也可以将图像放入主项目的Images文件夹中,并在xaml中引用它,如下所示:

<Setter Property="Icon">
    <Setter.Value>
        <Image Source="/ProjectName;component/Images/IconName.ico" />
    </Setter.Value>
</Setter>
Run Code Online (Sandbox Code Playgroud)

  • 我的上下文菜单显示:[System.Windows.media.Imaging.BitmapImage Refresh] (2认同)

Jon*_*han 5

对于仍在寻找解决方案的任何人,这对我有用:

<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>
Run Code Online (Sandbox Code Playgroud)