Question

I'm learning wpf with mvvm light and i'm face an issue. I've a usercontrol with a datagrid that's loaded with a query.

Now i'd like to add an event on the selectedIndex to retrieve the selected line and after that i'll pass the value to an other user control.

the issue is that my event is never fired.

Here is what i did

<DataGrid HorizontalAlignment="Left" Name="dgUser" VerticalAlignment="Top" SelectedIndex="{Binding SelectedIndex, Mode=TwoWay}" SelectedItem="{Binding selectedRow, Mode=TwoWay}"  Width="800" Height="253" >

Here is the code of my viewmodel

public RelayCommand selectedRow { get; private set; }
    private int _selectedIndex;
    public int SelectedIndex
    {
        get { return _selectedIndex; }
        set
        {
            _selectedIndex = value;
            RaisePropertyChanged("SelectedIndex");
        }
    }
    /// <summary>
    /// Initializes a new instance of the ListUserViewModel class.
    /// </summary>
    public ListUserViewModel()
    {
        selectedRow = new RelayCommand(() => SelectedRowChange());
        SelectedIndex = 2;
    }

    private void SelectedRowChange()
    {
        System.Windows.MessageBox.Show("test");
    }

My row is not selected with SelectedXIndex = 2 and nothing happen when i select an other row

Was it helpful?

Solution

You are trying to bind a Command on your ViewModel to the SelectedItem of your DataGrid and that's not quite how it works.

You want to hook into the DataGrid.SelectionChanged event and presumably fire your ViewModel's RelayCommand at that point.

Check this answer for a great explanation on how to do this in XAML.

EDIT:

To pass the SelectedItem to your RelayCommand as a command parameter, use the following in your XAML:

<i:Interaction.Triggers>
    <i:EventTrigger EventName="SelectionChanged">
        <i:InvokeCommandAction Command="{Binding MyCommand}" 
        CommandParameter="{Binding Path=SelectedItem, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=DataGrid}}" />
    </i:EventTrigger>
</i:Interaction.Triggers>

and ensure that you change your RelayCommand to be of the type you wish.

NOTE: You have not provided what the type of the items you have in your DataGrid, so I'll use object here.

public RelayCommand<object> selectedRow { get; private set; }

You can then rely on the command's parameter being the selected item:

public ListUserViewModel()
{
    selectedRow = new RelayCommand(i => SelectedRowChange(i));
    SelectedIndex = 2;
}

private void SelectedRowChange(object selectedItem)
{
    // selectedItem is the item that has just been selected
    // do what you wish with it here
    System.Windows.MessageBox.Show("test");
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top