我有一个带有 TreeView 和 ContextMenu DependencyProperty 的 UserControl:
public ObservableCollection<Control> ContextMenu {
get {
return ( ObservableCollection<Control> )GetValue( ContextMenuProperty );
}
set {
SetValue( ContextMenuProperty, value );
}
}
public static readonly DependencyProperty ContextMenuProperty =
DependencyProperty.Register( "ContextMenu", typeof( ObservableCollection<Control> ), typeof( FilterableTreeViewControl ),
new PropertyMetadata( new ObservableCollection<Control>(), new PropertyChangedCallback( FilterableTreeViewControl.OnContextMenuPropertyChange ) ) );
private static void OnContextMenuPropertyChange( DependencyObject d, DependencyPropertyChangedEventArgs e ) {
FilterableTreeViewControl ctrl = d as FilterableTreeViewControl;
ctrl.OnContextMenuChange( ( Object )e.NewValue );
}
protected virtual void OnContextMenuChange( Object NewItemsSource ) {
}
XAML:
<controlsToolkit:TreeViewDragDropTarget AllowDrop="True" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch" Drop="TreeViewDragDropTarget_Drop" AllowedSourceEffects="All">
<controlsToolkit:TreeViewDragDropTarget.Resources>
<Data:HierarchicalDataTemplate x:Key="TreeViewTemplate" ItemsSource="{Binding Children}">
<StackPanel Orientation="Horizontal" Height="Auto" Width="Auto">
<Image Source="{Binding Type,Converter={StaticResource TreeIconConverter}}" />
<TextBlock x:Name="NameTextBlock" Text="{Binding Name}">
<controlsInputToolkit:ContextMenuService.ContextMenu>
<controlsInputToolkit:ContextMenu ItemsSource="{Binding ElementName=MyTreeViewControl, Path=ContextMenu}" />
</controlsInputToolkit:ContextMenuService.ContextMenu>
</TextBlock>
</StackPanel>
</Data:HierarchicalDataTemplate>
</controlsToolkit:TreeViewDragDropTarget.Resources>
<Controls:TreeView Name="treeView" ItemTemplate="{StaticResource TreeViewTemplate}">
</Controls:TreeView>
</controlsToolkit:TreeViewDragDropTarget>
用法:
<my:MyControl
DragEnabled="False"
ItemsSource="{Binding TreeRootNodes}"
FilterCaption="Filter:"
SelectionChangedCommand="{Binding SelectedMachineGroupChangedCommand_L}"
DropCommand="{Binding DropCommand}">
<my:FilterableTreeViewControl.ContextMenu>
<controlsInputToolkit:MenuItem Header="Menu 1" />
<controlsInputToolkit:MenuItem Header="Menu 2" />
<controlsInputToolkit:MenuItem Header="Menu 3" />
</my:MyControl.ContextMenu>
</my:MyControl>
首先一切正常,但在第二个之后我显然得到“元素已经是另一个元素的子元素”。例外。
是否可以仅通过绑定来解决这个问题,而无需任何代码隐藏?