-3

I have a little problem about selecting all rows from a DataGrid. The question is that the CommandButton is in a UserControl which refers to the MainViewModel and the grid is in a UserControl which refers to another ViewModel. The first thought was to make a static method and call it from the mvm, but the datagrid is not static and can't be called. How can i do?

Edit:

I actually solved the problem by rferencing a static instance of the grid from the code behind.

In the pushbutton viewmodel i recalled the select all method inside the command execution

 if (_CommandBtnSelectAll == null)
 {
    // creo una nuova istanza del comando
    _CommandBtnSelectAll = new USCommands(
       item =>
       {
             ViewControlCodeBehind.grid.SelectAll();
       }
 }

In the ViewControl Code Behind i just had to set a static instance of a new DataGrid and assign it the actual datagrid.

public static DataGrid grid;

public ControlBody() // It's the UserControl initialization
{
   this.grid = DataGridControl; // DataGridControl is the name of the actual control
}
  • 1
    Marco: please add relevant code to your post so we can see how your xaml is structured. There's a very right chance that you can simply exploit the inherited DataContext of usercontrol & pass it into command as a CommandParameter that can then set a property on ViewModel (For example `foreach(var item in viewModel.Items) item.IsSelected = true;` This will then get automatically picked up by DataGrid (assuming ViewModel.Items was bound to DataGrid & IsSelected was bound to ItemContainer.IsSelected) You can do a search on SO for IsSelected binding if you need more info on how to bind it. – Maverik Aug 21 '19 at 10:11

1 Answers1

0

You could send a message or an event from the view model and subscribe to and handle this event in the view using a messenger or an event aggregator. Please refer to this blog post for more information about this.

The other option would be to inject the view model with an interface that the view implements as suggested here.

mm8
  • 163,881
  • 10
  • 57
  • 88