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

Sindhu Kalyanapu 21 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}"/>

Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,148 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
8,969 questions
{count} votes

Accepted answer
  1. Leon Lu (Shanghai Wicresoft Co,.Ltd.) 53,756 Reputation points Microsoft Vendor
    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