我在使用上下文菜单执行复制操作时随机获取异常 “无法将'MS.Internal.NamedObject'类型的对象强制转换为类型TreeItemViewModel”
以下是我的上下文菜单的代码
<ContextMenu x:Key="MyContextMenu" >
<ContextMenu.Resources>
<obj:BindingProxy x:Key="vmProxy" Data="{Binding RelativeSource={RelativeSource AncestorType=ContextMenu}, Path=PlacementTarget, Converter={StaticResource FindNamedElementFromSourceTreeConverter}, ConverterParameter=MyTreeView}"/>
<obj:BindingProxy x:Key="modelProxy" Data="{Binding RelativeSource={RelativeSource AncestorType=ContextMenu}, Path=PlacementTarget.DataContext}"/>
</ContextMenu.Resources>
<MenuItem Header="{core:Localization Key=Copy}"
CommandParameter="{Binding Source={StaticResource modelProxy}, Path=Data}"
Command="{Binding Source={StaticResource vmProxy}, Path=Data.DataContext.CopyCommand}">
</MenuItem>
</ContextMenu>
此上下文菜单用于我的树视图项目样式,如下所示
<Style x:Key="MyTreeViewItemStyle" TargetType="TreeViewItem">
<Style.Triggers>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource Self}, Path=DataContext, Converter={StaticResource TypeOfConverter}}" Value="{x:Type models:MyModel1}">
<Setter Property="ContextMenu" Value="{StaticResource MyContextMenu}"/>
</DataTrigger>
</Style.Triggers>
</Style>
此样式将添加到Treeview中,如下所示
<TreeView x:Name="MyTreeView"
DockPanel.Dock="Top"
Padding="0"
ItemsSource="{Binding MyTreeItems}"
BorderThickness="0"
ItemContainerStyle="{StaticResource MyTreeViewItemStyle}"/>
这是我的转换器
public class FindNamedElementFromSourceTreeConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
string name = parameter as string;
if (string.IsNullOrEmpty(name)) return null;
DependencyObject dp = value as DependencyObject;
if (dp == null) return null;
DependencyObject root = DependencyObjectHelper.FindRootElement(dp);
if (root == null) return null;
DependencyObject result = DependencyObjectHelper.FindChild(root, name);
return result;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
当通过右键单击treeviewItem上下文菜单项执行excecute copy命令时,会出现“无法转换类型对象”异常。 UI中的另一个按钮使用了相同的复制命令,该按钮工作正常,没有任何问题。请让我知道如何解决这个问题..