5

I am working on a C#-WPF-App.

When pressing a certain button in a window, a module is loaded. This happens because the Command Property of the button is bound to the LoadModuleCommand in the class "ConfigureViewModel":

<Button Command="{Binding LoadModuleCommand}" Margin="10,10,10,10" Grid.Column="1" Content="Add Module" Grid.Row="0" />

For some reason, which is not important for this question, I now also want to call the same command (i.e. the LoadModuleCommand) from the MainViewModel.cs-file, if a certain condition is true:

 if (id.Equals(Module.Id.ToString()))
        {
             //call the LoadModuleCommand

        }

I knew what I had to do, if I had to bind the LoadModuleCommand to a second UI-control. But how do I simply call the command from within c#-code?

steady_progress
  • 3,311
  • 10
  • 31
  • 62
  • 1
    Why don't you abstract what the command does into another class so you can reuse it anywhere? – Crowcoder Oct 15 '17 at 17:35
  • LoadModuleCommand calls some function xyz() ... I made this function (i.e. the xyz()-function) public and static and then tried to call it inside the if-block. THere was no error message but the module did not load ... I have no idea why it doesn't work – steady_progress Oct 15 '17 at 17:39

2 Answers2

3

There are several ways to solve your problem.

One approach is to take the bound data context and cast it. Now you are able to execute the command like

var viewModel = (ConfigureViewModel)DataContext;
if (viewModel.LoadModuleCommand.CanExecute(null))
{
    viewModel.LoadModuleCommand.Execute(null);
}

Note that you need to know the type of the data context to cast it correctly. Use an interface if there are several types possible.

A second way is to name the button (e.g. <Button x:Name="loadModuleButton" .../>) and raise the clicked event like

loadModuleButton.RaiseEvent(new RoutedEventArgs(ButtonBase.ClickEvent));
Fruchtzwerg
  • 10,999
  • 12
  • 40
  • 49
2

You said that you have a function xyz() that it is called from ConfigureViewModel and from MainViewModel. This function should be into another class that you can initialized in the constructor of every view model or better that this is to be send as parameter in the constructor by dependency injection. You have to bide a command us you did for ConfigureViewModel, also to MainViewModel and there to make your check.