Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
来自usercontrol的WPF relaycommand_Wpf_Routing_Command_Relaycommand - Fatal编程技术网

来自usercontrol的WPF relaycommand

来自usercontrol的WPF relaycommand,wpf,routing,command,relaycommand,Wpf,Routing,Command,Relaycommand,我是WPF新手,本着以正确方式做事的精神,我尝试在我的应用程序中实现MVVM。我利用了乔希·史密斯(Josh Smith)经常提到的文章,除了让我意识到自己所知甚少之外,它还让我有点困惑 具体来说,我有一个页面,它使用RelayCommand对象直接处理页面上的按钮,这很好。但是,按钮(保存)最终将位于用户控件上,该控件还将包含其他按钮,并且该控件将在多个页面上使用 我的问题是,;如何将命令从用户控件传递到包含它的页面(ie viewmodel)?如果我服从命令 public ICommand

我是WPF新手,本着以正确方式做事的精神,我尝试在我的应用程序中实现MVVM。我利用了乔希·史密斯(Josh Smith)经常提到的文章,除了让我意识到自己所知甚少之外,它还让我有点困惑

具体来说,我有一个页面,它使用RelayCommand对象直接处理页面上的按钮,这很好。但是,按钮(保存)最终将位于用户控件上,该控件还将包含其他按钮,并且该控件将在多个页面上使用

我的问题是,;如何将命令从用户控件传递到包含它的页面(ie viewmodel)?如果我服从命令

public ICommand SaveCommand
{
  get
  {
    if (_saveCommand == null)
    {
      _saveCommand = new RelayCommand(
          param => this.Save(),
          param => this.CanSave
          );
    }
    return _saveCommand;
  }
}
在用户控件上,我需要在用户控件本身上使用Save方法,而实际上我应该在viewmodel上处理它


有人能帮忙吗?

那么,您需要绑定到父级(页面)的DataContext(viewmodel)吗?尝试使用RelativeSource:

绑定到SaveCommand,那么,您需要绑定到父级(页面)的DataContext(viewmodel)吗?尝试使用RelativeSource绑定到SaveCommand:

尝试探索这一点。它将在绑定和中继命令方面对您有很大帮助

出于您的考虑,您需要绑定用户控件的datacontext。如果要使用保存命令的按钮。试试这个:

<Grid x:Name="LayoutRoot" DataContext="{ yourViewModelHere }">
      <Button x:Name="btnSave" Command="{Binding SaveCommand}"/>
</Grid>

尝试探索这一点。它将在绑定和中继命令方面对您有很大帮助

出于您的考虑,您需要绑定用户控件的datacontext。如果要使用保存命令的按钮。试试这个:

<Grid x:Name="LayoutRoot" DataContext="{ yourViewModelHere }">
      <Button x:Name="btnSave" Command="{Binding SaveCommand}"/>
</Grid>


谢谢!如果有人感兴趣,可以这样做;Command=“{Binding SaveCommand}”CommandParameter=“{Binding RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type UserControl}}}}”谢谢!如果有人感兴趣,可以这样做;Command=“{Binding SaveCommand}”CommandParameter=“{Binding RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type UserControl}}”