Search code examples
c#wpfmvvmdatagridrelaycommand

Cast Error occured in WFP DataGrid CurrentCellChanged While on Binding a RelayCommand


Inner Exception Message: Unable to cast object of type 'System.Reflection.RuntimeEventInfo' to type 'System.Reflection.MethodInfo'

<DataGrid CurrentCellChanged="{Binding CallCommand}" AutoGenerateColumns="False" ItemsSource="{Binding MobileList, UpdateSourceTrigger=PropertyChanged}" SelectionUnit="FullRow" IsReadOnly="True">
    <DataGrid.InputBindings>
        <KeyBinding Key="C" Modifiers="Ctrl" Command="{Binding Path=DataContext.CopyToClipBoardCommand}" CommandParameter="{Binding }" />
    </DataGrid.InputBindings>
    <DataGrid.Columns>
        <!--Column 1-->
        <DataGridTextColumn Binding="{Binding MobileName}" Header="Name" />
        <!--Column 2-->
        <DataGridTextColumn Binding="{Binding MobileOS}" Header="OS" />
    </DataGrid.Columns>
</DataGrid>

My RelayCommand Source Code:

public RelayCommand<KeyboardEventArgs> CallCommand
{
    get
    {
        return new RelayCommand<KeyboardEventArgs>((selectedItem) =>
        {

        });
    }
}

Kindly assist me, how to Bind the RelayCommand to the CurrentCellChanged property in a DataGrid using MVVM approach ?

Kindly Bind the Event Command to CurrentCellChanged Property.


Solution

  • Use System.Windows.Interactivity.dll for using interaction it is used for binding command to event thus, your MVVM pattern not violate.

    At the top in Window/Usercontrol you have to write namespace for using interaction,

    xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
    

    here,I put some xaml code for it.

     <DataGrid  AutoGenerateColumns="False" 
                       ItemsSource="{Binding MobileList, UpdateSourceTrigger=PropertyChanged}" 
                       SelectionUnit="FullRow" IsReadOnly="True" >
    
                <DataGrid.InputBindings>
                    <KeyBinding Key="C" Modifiers="Ctrl" Command="{Binding Path=DataContext.CopyToClipBoardCommand}" CommandParameter="{Binding }" />
                </DataGrid.InputBindings>
    
                <i:Interaction.Triggers>
                    <i:EventTrigger  EventName="CurrentCellChanged">
                        <i:InvokeCommandAction Command="{Binding Path=DataContext.CallCommand,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type Window}}}"/>
                    </i:EventTrigger>
                </i:Interaction.Triggers>
    
                <DataGrid.Columns>
    
                    <!--Column 1-->
                    <DataGridTextColumn Binding="{Binding MobileName}" Header="Name" />
                    <!--Column 2-->
                    <DataGridTextColumn Binding="{Binding MobileOS}" Header="OS" />
                </DataGrid.Columns>
            </DataGrid>