相关疑难解决方法(0)

带图标的MenuItem样式只创建一个图标

我在使用viewmodels作为ItemsSource的动态菜单渲染图标时遇到问题.
我使用的解决方案概述了 MVVM Dynamic Menu UI与ViewModel的绑定

基本布局如下

<Grid>
  <Grid.Resources>
    <HierarchicalDataTemplate DataType="{x:Type ViewModels:HeaderedItemViewModel}"
        ItemsSource="{Binding Path=Children}">
      <ContentPresenter RecognizesAccessKey="True"></ContentPresenter>
    </HierarchicalDataTemplate>
    <Style TargetType="{x:Type MenuItem}">
      <Setter Property="Header" Value="{Binding Path=Header}" />
      <Setter Property="InputGestureText" Value="{Binding Path=InputGestureText}" />
      <Setter Property="Command" Value="{Binding Path=Command}" />
      <Setter Property="Icon">
        <Setter.Value>
          <Image Source="{Binding Path=Icon}" Height="16px" Width="16px" />
        </Setter.Value>
      </Setter>
    </Style>
  </Grid.Resources>
  <Menu Grid.Row="0" ItemsSource="{Binding Path=Shell.Navigation.Menus}" />
</Grid>
Run Code Online (Sandbox Code Playgroud)

在上面的样式中,绑定'Icon'是'ImageSource'.其设置如下.

        BitmapImage image = null;

        if (!string.IsNullOrEmpty(imagePath))
        {
            image = new BitmapImage(new Uri(imagePath, UriKind.Relative));
            image.CacheOption = BitmapCacheOption.OnLoad;
            image.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
        }
        var menu = new HeaderedItemViewModel …
Run Code Online (Sandbox Code Playgroud)

wpf mvvm

24
推荐指数
1
解决办法
6397
查看次数

通过样式设置器设置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)

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

wpf xaml menuitem

5
推荐指数
2
解决办法
8288
查看次数

标签 统计

wpf ×2

menuitem ×1

mvvm ×1

xaml ×1