【发布时间】:2011-09-04 20:58:33
【问题描述】:
我在为使用视图模型作为 ItemsSource 的动态菜单呈现图标时遇到问题。
我使用的解决方案在此处概述
MVVM Dynamic Menu UI from binding with 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
};
我遇到的问题是图标。
似乎一次只会渲染一个图标?这就是我的意思。
然后打开下拉菜单...
一旦渲染另一张图像,第一张图像就会消失?换句话说,只有最后一个图像是可见的。菜单中的所有图像都会发生这种情况。有什么想法吗?
【问题讨论】:
-
一个问题:如何设置实际输入绑定,绑定到 InputGestureText 不会设置实际输入绑定。
-
我目前没有使用输入绑定。这可能会进一步帮助您。 blogs.msdn.com/b/llobo/archive/2009/10/29/…。通过扩展命令类,您可以将它们映射到来自 ViewModel 的输入 bingings 集合。
-
@bitbonk:是的,手势按照上面的定义绑定。我有一个名为 NavigationViewModel 的类,它创建和初始化所有菜单和工具栏。这些都派生自一个名为 HeaderItemViewModel 的类。这意味着我可以为同样出现在工具栏中的菜单项重用实例。这能回答你的问题吗?