我有一個ContextMenu
和一個button
,在TabControl
,我得到按鈕Command
工作正常,但不知道如何綁定Context menu items
命令。你能指出我做錯了什麼嗎?如何將命令綁定到祖先datacontext? WPF :: MVVM
注意:命令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>
視圖模型代碼:
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)類中聲明的正常工作。但我想要綁定命令ViewModel
目前UserControl
你看這個嗎? http://stackoverflow.com/questions/15033522/wpf-contextmenu-woes-how-do-i-set-the-datacontext-of-the-contextmenu – blins