How do you bind a command to a MenuItem (WPF)?

后端 未结 3 1437
既然无缘
既然无缘 2020-12-30 10:59

Here is my code from the View.xaml.cs:

private RelayCommand _closeCommand;
public ICommand CloseCommand
{
    get
    {
        if (_closeCommand == null)
           


        
相关标签:
3条回答
  • 2020-12-30 11:29

    ContextMenu is not part of the VisualTree, that's why the DataContext will not be inherited. Here ContextMenu.PlacementTarget is some kind of relay to get the Window:

    <MenuItem Name="menuItem_Close" Header="Close"
              Command="{Binding Path=PlacementTarget.DataContext.CloseCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}" />
    
    0 讨论(0)
  • 2020-12-30 11:31

    Old question, new answer. For me the problem was that GalaSoft.MvvmLight.Command.RelayCommand didn't support closures for the action. RelayCommand stores a weak reference to the action so a closure gets deallocated almost immediately. The action must be a model method or be retained in some other way.

    0 讨论(0)
  • 2020-12-30 11:35

    for binding cross visual tree, refer to

    Binding Visibility for DataGridColumn in WPF

    or jsut try search BindingProxy

    0 讨论(0)
提交回复
热议问题