[英]How to bind command to ancestor datacontext? WPF :: MVVM
我在TabControl
有一个ContextMenu
和一个button
,按钮Command
可以正常工作,但是无法弄清楚如何绑定Context menu items
命令。 您能指出我做错了什么吗?
注意 :将命令CloseTabCommand
和CloseAllTabsCommand
绑定到按钮时,它们都可以正常工作。
XAML代码:
<TabControl ItemsSource="{Binding TabItems}">
<TabControl.ItemTemplate>
<DataTemplate>
<DockPanel Width="120" ToolTip="{Binding HeaderText}">
<DockPanel.ContextMenu>
<ContextMenu>
<MenuItem Header="Close Tab"
Command="{Binding DataContext.CloseTabCommand, RelativeSource={RelativeSource AncestorType=TabControl}}"
CommandParameter="{Binding ItemId}" />
<MenuItem Header="Close All Tabs"
Command="{Binding DataContext.CloseAllTabsCommand, RelativeSource={RelativeSource AncestorType=TabControl}}" />
</ContextMenu>
</DockPanel.ContextMenu>
<Button
Command="{Binding DataContext.CloseTabCommand, RelativeSource={RelativeSource AncestorType=TabControl}}"
CommandParameter="{Binding ItemId}"
Content="X"
Cursor="Hand"
DockPanel.Dock="Right"
Focusable="False"
FontFamily="Courier"
FontWeight="Bold"
FontSize="10"
VerticalContentAlignment="Center"
Width="15" Height="15" />
<ContentPresenter Content="{Binding HeaderText}" VerticalAlignment="Center" />
</DockPanel>
</DataTemplate>
</TabControl.ItemTemplate>
<TabControl.ItemContainerStyle>
<Style TargetType="TabItem">
<Setter Property="IsSelected" Value="{Binding IsSelected}" />
</Style>
</TabControl.ItemContainerStyle>
</TabControl>
ViewModel代码:
private ObservableCollection<TabItemViewModel> _tabItems;
public ObservableCollection<TabItemViewModel> TabItems {
// if _tabItems is null initiate object.
get { return _tabItems; }
set { SetProperty(ref _tabItems, value); }
}
编辑:
绑定到在TabItemViewModel
(TabControl ItemsSource)类中声明的Command可以正常工作。 但我想将命令绑定到当前UserControl
ViewModel
将DockPanel的Tag属性绑定到视图模型,然后将MenuItem的Command属性绑定到ContextMenu的PlacementTarget:
<DockPanel Width="120" ToolTip="{Binding HeaderText}"
Tag="{Binding DataContext, RelativeSource={RelativeSource AncestorType=TabControl}}">
<DockPanel.ContextMenu>
<ContextMenu>
<MenuItem Header="Close Tab"
Command="{Binding PlacementTarget.Tag.CloseTabCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}"
CommandParameter="{Binding ItemId}" />
...
ContextMenu驻留在其自己的可视树中,这就是为什么您不能使用RelativeSource绑定到父TabControl的原因,因为可视树中没有父TabControl。
您是否尝试过将AncestorType绑定到Window或UserControl?
Command="{Binding CloseTabCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}}"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.