【发布时间】:2018-01-23 19:10:34
【问题描述】:
我无法将 contextMenu 中的选择绑定到我的命令 EditCommand。我的树视图中的按钮很好地绑定到它,但在菜单中它失败了。我读过这很可能是因为 contextMenu 位于不同的 UI 树中,但使用 findAncestor 和标签的解决方案对我不起作用。无论如何做绑定并且仍然能够将treeViewItem传递给该方法?
我的 XAML:
<TreeView Background="Transparent"
Margin="10"
Grid.Column="0" Grid.Row="1"
ItemsSource="{Binding Path=TreeViewItems}">
<TreeView.ItemTemplate >
<HierarchicalDataTemplate DataType="{x:Type model:TreeViewSelection}" ItemsSource="{Binding Configs}" >
<DockPanel HorizontalAlignment="Stretch" Background="Transparent"><!--Transparency allows context click on whole row-->
<DockPanel.ContextMenu>
<ContextMenu DataContext="{Binding PlacementTarget.DataContext, RelativeSource={RelativeSource Self}}">
<MenuItem
Header="Edit"
Command="{Binding ElementName=userControl, Path=DataContext.EditCommand}"<!--Doesn't work-->
CommandParameter="{Binding}">
<MenuItem.Icon>
<Image Source="../Images/edit.png" />
</MenuItem.Icon>
</MenuItem>
</ContextMenu>
</DockPanel.ContextMenu>
<TextBlock DockPanel.Dock="Left" Text="{Binding Title}" />
<StackPanel DockPanel.Dock="Right"
Orientation="Horizontal"
HorizontalAlignment="Right">
<Button Height="23" Width="23"
Command="{Binding ElementName=userControl, Path=DataContext.EditCommand}"<!--Works-->
CommandParameter="{Binding}"
Style="{DynamicResource ImageNoTextButton}"
inf:AttachedProperties.Image="../Images/edit.png"
inf:AttachedProperties.ImageMouseOver="../Images/editMouseOver.png" />
</StackPanel>
</DockPanel>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
【问题讨论】:
-
绑定相对源并通过
Command="{Binding PlacementTarget.DataContext.EditCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}"搜索祖先怎么样? -
@Peter,问题是我正在尝试绑定到 UserControl 数据上下文(这个 sn-p 在视图模型中的视图)