Relative binding in C#?

FranciscoGGFranciscoGG ESMember ✭✭
edited September 2015 in Xamarin.Forms

Hi to all.

I am implementing a custom **ViewCell **in code, and I want to bind the Command property of a button inside the ViewCell to a command in my ViewModel.

In XAML, I can do it:

<Button Text="Ok" Command="{Binding Path=BindingContext.ChosenItemCommand, Source={x:Reference Name=ItemsListView}}"/>

But how can I do this with C#?


Best Answer


  • TorbenKruseTorbenKruse DEMember ✭✭✭

    this._button.Command = ViewModel.ChosenItemCommand;

  • FranciscoGGFranciscoGG ESMember ✭✭

    @TorbenKruse , that button is child of a ViewCell, so, the DataContext is not the ViewModel class, is my Item class.

  • TorbenKruseTorbenKruse DEMember ✭✭✭

    Ok, sorry, I missed that.

    One way to do this is to extend your ViewCell with a ButtonClickedCommand and forward that to the actual Command of the Button. Then bind that when you create your DataTemplate of your custom ViewCell.

  • FranciscoGGFranciscoGG ESMember ✭✭
    edited September 2015

    @TorbenKruse , this is not my problem, maybe you don't have understood me...

    I know how to do the binding in XAML, and my question is if it is possible to do this binding on the same way but in C#.


  • TorbenKruseTorbenKruse DEMember ✭✭✭

    Yes. And that's what I explained.

  • FranciscoGGFranciscoGG ESMember ✭✭

    @TorbenKruse , I don't understand your aproach :(

  • TorbenKruseTorbenKruse DEMember ✭✭✭

    Can you share your ViewCell code and where you create your DataTemplate for your ListView. Ill then can try to make it more clear.

  • FranciscoGGFranciscoGG ESMember ✭✭
    edited September 2015


      <controls:ListView x:Name="ItemsListView" Grid.Row="1" Style="{StaticResource AppListView}" ItemsSource="{Binding Items}">
            <controls:SelectableItemCell />
  • FranciscoGGFranciscoGG ESMember ✭✭


  • FranciscoGGFranciscoGG ESMember ✭✭

    Thank you @TorbenKruse :)

  • AlexBekkerAlexBekker DEMember
    edited September 2015

    Hey guys,
    Im dealing with the same issue right now.

    I wasnt really able to grasp

    dataTemplate.SetBinding(SelectableItemCell.ButtonClickCommandProperty, this.ViewModel.ButtonCommand);

    this part. @TorbenKruse
    Isnt second parameter supposed to be a BindingBase?

  • TorbenKruseTorbenKruse DEMember ✭✭✭

    Yes, I just wrote that from top of my head, this is indeed incorrect.

Sign In or Register to comment.