Alex
Alex

Reputation: 294

Calling a method of a UserControl somewhere in MVVM

I have the following scenario:

  1. I have a user control, let's say UserControl.xaml
  2. In the code behind of this control I have the method DoSomething()
  3. I have viewmodel for this control UserControlViewModel.cs

I need to call usercontrol's DoSomething() method somewhere. Any ideas how to accomplish this?

Thanks!

Upvotes: 0

Views: 1038

Answers (3)

Peregrine
Peregrine

Reputation: 4556

It sounds as though your application is incorrectly structured.

What does

DoSomething()

do, that isn't reacting to a change in a bound property of the ViewModel?

If you really need to trigger something in the code behind of the View from the ViewModel, use a messaging handler such as the one in the Galasoft MVVMLight framework.

Upvotes: 0

Phil
Phil

Reputation: 43021

If I really had to do this, then using the DataContextChanged event may help. Here's a solution with hopefully minimal coupling between the view and the view-model.

public partial class MainWindow : IMainWindow
{
    public MainWindow()
    {
        this.DataContextChanged += this.MainWindowDataContextChanged;

        this.InitializeComponent();
    }

    private void MainWindowDataContextChanged(object sender, 
                     DependencyPropertyChangedEventArgs e)
    {
        var vm = this.DataContext as IMainWindowViewModel;
        if (vm != null)
        {
            vm.View = this;
        }
    }

    public void DoSomething()
    {
        Debug.WriteLine("Do something in the view");
    }
}

public interface IMainWindow
{
    void DoSomething();
}

public class MainWindowViewModel : IMainWindowViewModel
{
    public MainWindowViewModel()
    {
        this.DoSomethingCommand = new RelayCommand(this.DoSomething);
    }

    public ICommand DoSomethingCommand { get; set; }

    private void DoSomething()
    {
        Debug.WriteLine("Do something in the view model");

        var view = this.View;
        if (view != null)
        {
            view.DoSomething();
        }
    }

    public IMainWindow View { get; set; }
}

public interface IMainWindowViewModel
{
    IMainWindow View { get; set; }
}

Upvotes: 1

devdigital
devdigital

Reputation: 34369

You really should be using an MVVM framework if you're doing MVVM. A framework would provide a mechanism from which you can invoke a verb (method) on your view model from your view. Caliburn.Micro for example provides Actions.

Upvotes: 0

Related Questions