Button command is not working with Binding context in xamarin forms using MVVM

Sk 66 Reputation points
2023-09-01T09:20:53.31+00:00

If we give BindingContext value for button , then button command is not hitting on click event in xamarin forms with MVVM architecture.

From the below code snippet I have given BindingContext value as 1. So, when I click on Button the command is not working

Ex:

                            <Button BindingContext="1" Text="Retry" Command="{Binding PairConductorSensorCommand}" HorizontalOptions="FillAndExpand" IsVisible="False" Style="{StaticResource FormButton}"/>

Developer technologies .NET Xamarin
Developer technologies C#
{count} votes

Accepted answer
  1. Anonymous
    2023-09-04T08:22:04.6733333+00:00

    Hello,

    You can do this by adding Xamarin.Forms Bindable Properties when you create BorderlessEntry.cs like following code.

    public class BorderlessEntry : Entry
        {
            
            public static readonly BindableProperty ControlIndexProperty =
      BindableProperty.Create("ControlIndex", typeof(int), typeof(BorderlessEntry), -1);
            public int ControlIndex
            {
                get { return (int)GetValue(ControlIndexProperty); }
                set { SetValue(ControlIndexProperty, value); }
            }
        }
    

    Then you can set ControlIndex="1" in the xaml like following code, please remove the BindingContext="1"

          <local:BorderlessEntry x:Name="tbx_Conductor_Sensor_MAC_ID_1"  ControlIndex="1" Text="{Binding TbxConductorSensorMacID1Text}">
    

    Then you can get this BorderlessEntry in the viewmodel and get the controlindex as well.

    ConductorSensorMacIDTextChangeCommand = new Command((e) =>
                {
    
                   BorderlessEntry rs = e as BorderlessEntry;
    
                   Console.WriteLine("============"+rs.ControlIndex + "============");
                });
    

    Best Regards,

    Leon Lu


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.