Connect the selected row event to the mvvmlight command

I am writing a WPF application using MVVMLight. I have a DataGrid and I want to hook up a row select event for the command. This is the easy part. The hard part (for me, of course;]) is to get the object that is associated with the selected line. How can i do this?

+3
source share
1 answer

You have many ways to do this.

The first would be to pass the selected line as a parameter to the command. You can do this using XAML or code.

<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 property of the selected item in your view model and associate it with 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
        }
    }
}
+7
source

All Articles