@Rachel's solution is excellent. Using an interface makes it more loosely coupled:
using System.Windows.Input;
namespace WpfApplication
{
public interface IResetCaller
{
ICommand ResetCommand { get; set; }
}
}
Ask the base view model to implement this interface, for example.
public class MyViewModel : ModelBase, IResetCaller
{
...
public ICommand RefreshSegmentCommand { get; set; }
}
And the Rachel code becomes:
private void MyUserControl_Loaded(object sender, RoutedEventArgs e)
{
var ctrl = sender as FrameworkElement;
if (ctrl == null) return;
var vm = ctrl.DataContext as IResetCaller;
if (vm == null)
return;
vm.ResetCommand = new RelayCommand(param => this.Reset(param));
}
This interface can be used to decorate any number of view models, and the interface can be defined in the same library as UserControl. In the main ViewModel, you simply do something like ResetCommand.Execute(this)or any other parameter that you want to pass.
source
share