Search code examples
c#mvvmtelerikradgridview

Telerik RadGridView insert new row MVVM


I have a RadGridView inside my view and I am binding its ItemSource to a list inside my ViewModel. Everything works fine. But how do I insert a new row with a MVVM approach. I would rather not use code-behind for that.

<telerik:RadGridView x:Name="radGridView" Grid.Row="1" ShowGroupPanel="False" IsFilteringAllowed="False" ItemsSource="{Binding Lieferadressen}" ColumnWidth="*" />

Does anyone know how to achieve that?

I can't find anything on the Telerik documentation about inserting new rows with MVVM.


Solution

  • I figured it out on my own and I am gonna post my answer for those struggling with it.

    So the basic approach is to use Interaction Triggers. For which you have to add the System.Windows.Interactivity package to your project via NuGet.

    Then add the follwing 2 namespaces inside your xaml file which contains your RadGridView:

    xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
    xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
    

    Then you configure your RadGridView with the Triggers.

    <telerik:RadGridView x:Name="radGridView" Grid.Row="1" ShowGroupPanel="False" IsFilteringAllowed="False" ItemsSource="{Binding Lieferadressen}" ColumnWidth="*">
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="RowEditEnded">
                <ei:CallMethodAction TargetObject="{Binding}" MethodName="OnLieferadresseRowEditEnded" />
            </i:EventTrigger>
        </i:Interaction.Triggers>
    </telerik:RadGridView>
    

    The EventName is important here.

    Then in your ViewModel:

    public void OnLieferadresseRowEditEnded(object sender, GridViewRowEditEndedEventArgs e)
    {
        var row = e.Row as GridViewRow;
    
        if (e.EditAction == GridViewEditAction.Cancel)
        {
            return;
        }
        else if (e.EditOperationType == GridViewEditOperationType.Insert)
        {
            //Insert the entry in the data base
        }
        else if (e.EditOperationType == GridViewEditOperationType.Edit)
        {
            //Update the entry in the data base
        }
    }