问题描述
|
我在渲染使用视图模型作为ItemsSource的动态菜单的图标时遇到问题。
这里概述了我使用的解决方案
MVVM动态菜单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>
在上面的样式中,绑定\'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
{
Header = header,InputGestureText = inputGesture,ImagePath = imagePath,Icon = image,Command = command,IsEnabled = isEnabled
};
我遇到的问题是图标。
似乎一次只能显示一个图标?这是我的意思。
并打开下拉菜单...
一旦渲染了另一个图像,第一个图像就消失了吗?换句话说,只有最后一张图像可见。菜单中的所有图像都会发生这种情况。有任何想法吗?
解决方法
为您的Icon值添加x:Shared = false。
为此,您应该在资源中声明Image:
<Grid>
<Grid.Resources>
<Image x:Key=\"imgCTX\" x:Shared=\"false\"
Source=\"{Binding Path=Icon}\" Height=\"16px\" Width=\"16px\"/>
<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\" Value=\"{StaticResource imgCTX}\" />
</Style>
</Grid.Resources>
<Menu Grid.Row=\"0\" ItemsSource=\"{Binding Path=Shell.Navigation.Menus}\" />
</Grid>