Binding to base viewmodel command from View

I have a base viewModel and two derived viewModels from it. In my base viewModel I have some commands CloseCommand, CancelCommand etc.

My View is attached to one of the derived viewModels. I need to bind a button to the CloseCommand in the base viewModel. How can I do this with inheritance?

I have bind the button's content with string property from base viewModel and its working fine but how can I bind a command?


There is nothing special u need to do to bind those commands as far as they are exposed as Public properties of your ViewModel. I had the same situation so here is my very owne implementation of how I did that.

First of all in your base class define OKCommand / CancelCommand of type ICommand. as far es Execute and CanExecute methods are concerned, I have them defined as protected virtual Methods (By The way u can also define your Commands as Virtual. this will give u ability to write XAML style which sets visibility mode of button to collapsed if its Command Value is null). Inside your derived ViewModels u simply override commands, Execute and CanExecute methods as needed but from your view u always simply bind to command names directly.

below is an example of what I have just explained to u.

public abstract class ViewModelbase
{
    private DelegateCommand _okCommand;
    public virtual DelegateCommand OkCommand
    {
        get { return _okCommand ?? (_okCommand = new DelegateCommand(OkExecuteCommand, CanOkExecute)); }
    }

    protected virtual void OkExecuteCommand()
    {
        DialogResult = true;
    }

    protected virtual bool CanOkExecute()
    {
        return IsValid;
    }
}

Then u simply define your concrete ViewModel classes which are derived from base ViewModel class

public class SampleViewModel : ViewModelbase
{
   //If u have defined XAML style which sets viability of button as collapsed if its command value is null u simply override command
   public override DelegateCommand OkCommand { get { return null; } }
    protected override void OkExecuteCommand()
    {
        do whatever u want as this is a command execution
    }
}

in XAML part u do not have to do anything special just bind your buttons command to Viewmodel Command as you would do if there was no Base class. The key point here is that you Should expose your commands from your base ViewModel class with public modifier (u need only getter so this code provides sample of one way u can expose commands)


Nothing special, here's what you need to do:

  • Set the DataContext of your View to your derived ViewModel
  • Ensure that the CloseCommand, for example, is declared as a public property in your ViewModelBase
  • Set the Button's Command property to "{Binding CloseCommand}"
  • 链接地址: http://www.djcxy.com/p/56166.html

    上一篇: WPF + MVVM:如何在需要DependencyProperty时使用普通的ViewModelBase

    下一篇: 绑定到View的基本viewmodel命令