Wpf 从资源字典加载数据模板
在WPF客户端应用程序中,我在使用分层数据模板加载数据绑定菜单项时遇到了一些困难 首先,我创建了ViewModel,其中包含菜单项的基本属性:标题、命令、图像源路径,以用于图标属性和子项 然后,我在XAML窗口中创建了视图来显示我的菜单。为了绑定我的集合,考虑到子项,我使用了菜单项模板的分层数据模板 以下是ItemTemplate的XAML代码:Wpf 从资源字典加载数据模板,wpf,image,data-binding,menuitem,hierarchicaldatatemplate,Wpf,Image,Data Binding,Menuitem,Hierarchicaldatatemplate,在WPF客户端应用程序中,我在使用分层数据模板加载数据绑定菜单项时遇到了一些困难 首先,我创建了ViewModel,其中包含菜单项的基本属性:标题、命令、图像源路径,以用于图标属性和子项 然后,我在XAML窗口中创建了视图来显示我的菜单。为了绑定我的集合,考虑到子项,我使用了菜单项模板的分层数据模板 以下是ItemTemplate的XAML代码: <HierarchicalDataTemplate DataType="{x:Type vm:MenuItemViewModel}" Items
<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'只能用于
编译的资源字典
在花了这么多时间寻找解决方案之后,我终于制作了一个测试项目来演示这个问题
我不知道如何使我的资源字典成为已编译的资源字典。。。
有人能帮我吗?尝试从元素中删除x:Shared=false找到解决方案,实现转换器: 公共类菜单转换器:IValueConverter { 区域转换器成员 公共对象Convertobject值,类型targetType,对象参数,System.Globalization.CultureInfo区域性 { 如果值==null,则返回Binding.DoNothing; 字符串imageUri=value.ToString; 如果string.IsNullOrEmptyimageUri返回Binding.DoNothing; BitmapImage BitmapImage=new BitmapImagenew UriimageUri,UriKind.RelativeOrAbsolute{DecodePixelHeight=16,DecodePixelWidth=16}; 返回新图像{Height=16,Width=16,Source=bitmapImage,SnapsToDevicePixels=true,UseLayoutRounding=true}; } 公共对象ConvertBackobject值,类型targetType,对象参数,System.Globalization.CultureInfo区域性 { 不做任何事; } 端区 } 要使用转换器,应修改DataTemplate: 有了这个,一切都很好。
我期待的解决方案没有代码隐藏,但似乎不可能:如果删除属性,则只显示列表中的最后一幅图像