我在使用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
{
Header = header,
InputGestureText = inputGesture,
ImagePath = imagePath,
Icon = image,
Command = command,
IsEnabled = isEnabled
};
Run Code Online (Sandbox Code Playgroud)
我遇到的问题是图标.
似乎一次只会渲染一个图标?这是我的意思.

然后打开下拉菜单......

一旦渲染了另一个图像,第一个图像就会消失?换句话说,只有最后一个图像是可见的.菜单中的所有图像都会发生这种情况.有任何想法吗?
Paw*_*lSt 40
为您的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>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6397 次 |
| 最近记录: |