所以我一直在這一整天與我的頭靠在牆上。在我的WPF應用程序(使用MVVM Light)中,我有一個綁定到viewmodels集合的上下文菜單,它的行爲不太正確。我可以創建我的菜單,並且一切正常,我的MenuItems行爲樹,正在執行的命令以及正確的參數都會通過。我使用它來創建一個允許用戶添加項目到文件夾的上下文菜單。WPF - MenuItem與兒童沒有發射綁定命令
我碰到的問題是,當上下文菜單項有子項時,命令不再被觸發。因此,我只能將項目添加到沒有子文件夾的文件夾。
我已經使用Snoop調查了這一點,並且我的DataContext正確顯示了MenuItem,並且命令綁定正確,並且mousedown事件確實被觸發。
我遇到的問題是,如果一個MenuItem有孩子,它的命令不會被執行。任何沒有孩子的項目,命令沒有問題。
我真的很茫然,關於Stack Overflow或MSDN社交的每一個類似問題都沒有答案。
我已經在風格中設置了我的綁定。
<utility:DataContextSpy x:Key="Spy" />
<!-- Context style (in UserControl.Resources) -->
<Style x:Key="ContextMenuItemStyle" TargetType="{x:Type MenuItem}">
<Setter Property="Header" Value="{Binding Header}"/>
<Setter Property="ItemsSource" Value="{Binding Children}"/>
<Setter Property="Command" Value="{Binding Command}" />
<Setter Property="CommandParameter" Value="{Binding DataContext, Source={StaticResource Spy}" />
<Setter Property="CommandTarget" Value="{Binding Path=PlacementTarget, RelativeSource={RelativeSource AncestorType=ContextMenu}}"/>
</Style>
<!-- Later in the control -->
<ContextMenu ItemContainerStyle="{StaticResource ContextMenuItemStyle}" ItemsSource="{Binding MenuItems}" />
注意,DataSpy來自這篇文章,作品所描述的,讓我用我的usedcontrol的DataContext的爲命令參數
http://www.codeproject.com/Articles/27432/Artificial-Inheritance-Contexts-in-WPF
下面是用於視圖模型上下文菜單
public interface IContextMenuItem
{
string Header { get; }
IEnumerable<IContextMenuItem> Children { get; }
ICommand Command { get; set; }
}
public class BasicContextMenuItem : ViewModelBase, IContextMenuItem
{
#region Declarations
private string _header;
private IEnumerable<IContextMenuItem> _children;
#endregion
#region Constructor
public BasicContextMenuItem(string header)
{
Header = header;
Children = new List<IContextMenuItem>();
}
#endregion
#region Observables
public string Header
{
get { return _header; }
set
{
_header = value;
RaisePropertyChanged("Header");
}
}
public IEnumerable<IContextMenuItem> Children
{
get { return _children; }
set
{
_children = value;
RaisePropertyChanged("Children");
}
}
public ICommand Command { get; set; }
#endregion
}
這裏有一個上下文項實際上是路 用過的。
MenuItems = new List<IContextMenuItem>
{
new BasicContextMenuItem("New Folder") { Command = NewFolderCommand} ,
new BasicContextMenuItem("Delete Folder") { Command = DeleteFolderCommand },
new BasicContextMenuItem("Rename") { Command = RenameFolderCommand },
};
public ICommand NewFolderCommand
{
get { return new RelayCommand<FolderViewModel>(NewFolder); }
}
private void NewFolder(FolderViewModel viewModel)
{
// Do work
}
你說的命令不觸發? – Nitin
'public ICommand Command {get;組; }初始化? – CarbineCoder
@nit我剛剛更新了這個問題,因爲實際問題可能不太清楚。 我遇到的問題是,如果一個MenuItem有孩子,它的命令不會被執行。任何沒有孩子的項目,命令沒有問題。 – catkins