我在使用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)