Search code examples
wpfwpfdatagrid

Connecting selected row event to mvvmlight command


I'm writing WPF application, that's using MVVMLight. I have a DataGrid and I wanna connect event of selecting row to command. That's the easy part. The hard(for me of course ;]) part is to get the entity that's connected with the selected row. How can I do that?


Solution

  • You have many ways of doing so.

    The first one would be to pass the selected row as a command parameter. You can do this by XAML or code-behind.

    <GridView x:Name="gv">
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="SelectionChanged">
                <i:InvokeCommandAction Command="{Binding SelectedRowCommand}"
                                       CommandParameter="{Binding Path=SelectedItem, ElementName=gv}" />
            </i:EventTrigger>
        </i:Interaction.Triggers>
    </GridView>
    

    You can also create a selected item property in your view model and bind it to your control.

    <GridView x:Name="gv" SelectedItem="{Binding SelectedRow, Mode=TwoWay}">
    </GridView>
    
    public class MyViewModel
    {
        public RowType SelectedRow
        {
            get { return _selectedRow; }
            set
            {
                _selectedRow = value;
                // selection changed, do something here
            }
        }
    }