Accessing to object sender in MVVM approach

Topics: Questions
Jan 1, 2013 at 5:19 PM

How can i write command for the below code:

private void btnReportPay_Click(object sender, RoutedEventArgs e)
{
      Payment pay = ((Control)sender).DataContext as Payment;
      ReportHelper.ReportPayment(pay.Id);
}

Coordinator
Jan 2, 2013 at 2:47 PM

Why do you even have a btnReportPay_Click? That is not needed. You can add a command to your VM. In the VM, you know the payment (it's part of the VM). Then, you can do this:

ReportHelper.ReportPayment(Payment.Id);

Even better is to use services like this:

ReportService : IReportService which has a method ReportPayment. Then you can inject it into the constructor of the view model (all done automatically for you by catel).

Jan 2, 2013 at 4:51 PM
GeertvanHorrik wrote:

Why do you even have a btnReportPay_Click? That is not needed. You can add a command to your VM. In the VM, you know the payment (it's part of the VM). Then, you can do this:

 

Thanks for response. I have a datagrid for showing a collection of Pays and each row has a button for report the pay.

your solution is good when i want to report SelectedPay but in this case i want to know which row report button is clicked.

Regards

Jan 3, 2013 at 8:21 AM

You can try to use relativesource. Something llike this http://stackoverflow.com/questions/4500729/how-to-use-binding-in-the-listboxs-items-to-the-viewmodels-properties

Jan 3, 2013 at 5:34 PM
Edited Jan 3, 2013 at 5:34 PM

I can't figure out how to use relative source for this issue. Please explain more.

i use this markup in xaml:

 

<telerik:GridViewColumn MaxWidth="50" MinWidth="50">
      <telerik:GridViewColumn.CellTemplate>
              <DataTemplate>
                     <Button Name="btnReportPay" Click="btnReportPay_Click">
                           <Image Source="/UI;component/Resources/Images/Print.png" />
                       </Button>
               </DataTemplate>
       </telerik:GridViewColumn.CellTemplate>
</telerik:GridViewColumn>

 

and this is my code behind:

 

private void btnReportPay_Click(object sender, RoutedEventArgs e)
{
      Payment pay = ((Control)sender).DataContext as Payment;
      ReportHelper.ReportPayment(pay.Id);
}
thanks.
Coordinator
Jan 4, 2013 at 11:41 AM

Try to use this:

<Button Command="{Binding ReportPayCommand}" CommandParameter="{Binding Payment}">
In your command, you must accept the parameter type as command.