【发布时间】:2012-09-03 05:17:54
【问题描述】:
在 WPF 客户端应用程序中,我在使用分层数据模板加载数据绑定菜单项时遇到了一些困难。
首先,我创建了 ViewModel,其中包含菜单项的基本属性:标题、命令、ImageSource(用于图标属性的图像的路径)和子项。
然后,我在 XAML 窗口中创建了视图以显示我的菜单。为了绑定我的集合,考虑到子项,我为菜单项模板使用了分层数据模板。
这是 ItemTemplate 的 XAML 代码:
<HierarchicalDataTemplate DataType="{x:Type vm:MenuItemViewModel}" ItemsSource="{Binding Path=Items}">
<HierarchicalDataTemplate.ItemContainerStyle>
<Style TargetType="MenuItem">
<Style.Resources>
<Image x:Key="ItemImage" Source="{Binding ImageSource}" Width="16" Height="16" x:Shared="false" />
</Style.Resources>
<Style.Setters>
<Setter Property="Command" Value="{Binding Command}" />
<Setter Property="CommandParameter" Value="{Binding CommandParameter}" />
<Setter Property="Icon" Value="{StaticResource ItemImage}" />
</Style.Setters>
</Style>
</HierarchicalDataTemplate.ItemContainerStyle>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Title}" />
</StackPanel>
</HierarchicalDataTemplate>
当我初始化菜单并显示窗口时,一切看起来都很好。
之后,我尝试将菜单项模板放入资源字典中,以便能够在我的应用程序中的任何位置将其作为默认模板重用。 当我这样做时,我会抛出一个异常:
命名空间中的共享属性 'http://schemas.microsoft.com/winfx/2006/xaml' 只能用于 编译资源字典。
花了这么多时间寻找解决方案,我终于做了一个测试项目(here)来演示这个问题。
我不知道如何使我的资源字典成为编译资源字典... 谁能帮帮我?
【问题讨论】:
标签: wpf image data-binding menuitem hierarchicaldatatemplate