WPF上下文菜单命令绑定

时间:2016-07-27 11:48:24

标签: c# wpf xaml mvvm

我在SO中尝试了一些解决方案,但仍然无法触发命令。

XAML:

 <Image Source="{Binding CurrentImage.Source, Mode=OneWay}" Grid.Row="0" Grid.Column="1" Tag="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType= Window}}">
     <Image.ContextMenu>
            <ContextMenu DataContext="{Binding PlacementTarget.Tag, RelativeSource={RelativeSource Self}}">
                  <MenuItem Header="Edit Image" Command="{Binding PlacementTarget.Tag.EditImageCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ContextMenu}}"></MenuItem>
            </ContextMenu>
     </Image.ContextMenu>

视图模型:

private ICommand _EditImageCommand;
public ICommand EditImageCommand
   {
      get
        {
           return _EditImageCommand ?? (_EditImageCommand = new CommandHandler(() => EditImage(), _canExecute));
        }
   }

 public void EditImage()
 {

 }

3 个答案:

答案 0 :(得分:2)

变化:

private ICommand _EditImageCommand;
private ICommand EditImageCommand
   {
      get
        {
           return _EditImageCommand ?? (_EditImageCommand = new CommandHandler(() => EditImage(), _canExecute));
        }
   }

 public void EditImage()
 {

 }

private ICommand _EditImageCommand;
public ICommand EditImageCommand // has to be public
   {
      get
        {
           return _EditImageCommand ?? (_EditImageCommand = new CommandHandler(() => EditImage(), _canExecute));
        }
   }

 public void EditImage()
 {

 }

为了正确起见,必须公开命令(或内部命令)。

另外,将您的xaml更改为:

<Image Source="{Binding CurrentImage.Source, Mode=OneWay}" Grid.Row="0" Grid.Column="1" Tag="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType= Window}}">
     <Image.ContextMenu>
            <ContextMenu DataContext="{Binding PlacementTarget.Tag, RelativeSource={RelativeSource Self}}">
                  <MenuItem Header="Edit Image" Command="{Binding EditImageCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ContextMenu}}"></MenuItem>
            </ContextMenu>
     </Image.ContextMenu>

答案 1 :(得分:1)

已将我的XAML更改为,

<Window.Resources>
        <local:ImageList x:Key="SliderViewModel"></local:ImageList>
</Window.Resources>

    <Image Source="{Binding CurrentImage.Source, Mode=OneWay}" Grid.Row="0" Grid.Column="1">
        <Image.ContextMenu>
               <ContextMenu>
                     <MenuItem Header="Edit Image" Command="{Binding EditImageCommand, Source={StaticResource SliderViewModel}}"></MenuItem>
                 </ContextMenu>
         </Image.ContextMenu>
     </Image>

工作正常。感谢

答案 2 :(得分:1)

另一个不错的解决方法是在App.xaml中声明视图模型的静态实例:<ViewModelTypeName x:Key="ViewModelName" d:IsDataSource="True" />并像这样绑定Command="{Binding Source={StaticResource ViewModelName}, Path=MyCommand}"当我需要从Window和menuitem绑定时,我遇到了同样的问题&# 39;同时使用本机DataContext。此解决方案看起来并不复杂。