views:

50

answers:

2

Hi,

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?

A: 

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

Win4ster
Thanks!In case anyone is interested, it can be done like this;Command="{Binding SaveCommand}" CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}"
pilsdumps
A: 

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>
xscape