来自用户控件的 WPF 中继命令

发布于 2024-08-28 02:15:04 字数 594 浏览 5 评论 0原文

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

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

我的问题是这样的;如何将命令从用户控件中继到包含它的页面(即视图模型)?如果我绑定到用户控件上的命令

public ICommand SaveCommand
{
  get
  {
    if (_saveCommand == null)
    {
      _saveCommand = new RelayCommand(
          param => this.Save(),
          param => this.CanSave
          );
    }
    return _saveCommand;
  }
}

,我将需要在用户控件本身上使用 Save 方法,而实际上我应该在视图模型上处理它。

有人可以帮忙吗?

I'm new to WPF and in the spirit of trying to do things the correct way have tried to implement MVVM in my application. I've made use of the frequently mentioned article by Josh Smith, and apart from making me realise how little I know, it has left me a little stumped.

Specifically, I have a page that uses the RelayCommand object to handle a button directly on the page and this is fine. However, the button (save) will ultimately be on a user control that will also contain other buttons and the control will be used on a number of pages.

My question is this; how do I relay the command from the user control to the page (ie viewmodel) containing it? If I bind to the command

public ICommand SaveCommand
{
  get
  {
    if (_saveCommand == null)
    {
      _saveCommand = new RelayCommand(
          param => this.Save(),
          param => this.CanSave
          );
    }
    return _saveCommand;
  }
}

on the user control, I would need to use a Save method on the user control itself, when in fact I should be handling it on the viewmodel.

Can anyone help?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

眼眸里的快感 2024-09-04 02:15:04

那么,您需要绑定到父级(页面)的 DataContext (视图模型)吗?尝试使用RelativeSource绑定到SaveCommand: http://msdn.microsoft.com/en -us/library/ms743599.aspx

So, you need to bind to parent's(page) DataContext (viewmodel)? Try binding to SaveCommand using RelativeSource: http://msdn.microsoft.com/en-us/library/ms743599.aspx

原来分手还会想你 2024-09-04 02:15:04

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

考虑到您的担忧,您需要绑定用户控件的数据上下文。如果您要使用按钮来执行保存命令。试试这个:

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

Try to explore this one. It will help you a lot it terms of binding and relay command.

With your concern, you need to bind the user control's datacontext. If your going to use a button for your save command. try this:

<Grid x:Name="LayoutRoot" DataContext="{ yourViewModelHere }">
      <Button x:Name="btnSave" Command="{Binding SaveCommand}"/>
</Grid>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文