how do I call a method that is in the ViewModel for the code behind

Bruno Silva 26 Reputation points
2022-07-07T19:50:15.707+00:00

I need help to know how I can pull a function that is in my ViewModel, executing it in my code behind

Developer technologies | .NET | Xamarin
{count} votes

Accepted answer
  1. Yonglun Liu (Shanghai Wicresoft Co,.Ltd.) 50,126 Reputation points Microsoft External Staff
    2022-07-12T05:55:03.353+00:00

    Hello,

    Please provide minimal code to just what is needed to reproduce the problem.

    You could cast the BindingContext of your page to your ViewModel type and call it in the code behind, such as the following code:

       BindingContext = new HomePageViewModel(vn, vnUser, navigation);  
       var viewModel = BindingContext as HomePageViewModel;  
         
       // Then, you could call your methods from viewModel.  
       viewModel.OpenPadlock();  
    

    It is recommended to make a Command on your ViewModel, then in xaml file you could use BindingContext to call methods by Command or Event.

    If you call method from ViewModel directly, it will break the MVVM Pattern. Could you please provide the reason you want to call method from the ViewModel?

    You could refer to the following documentations:

    Best Regards,

    Alec Liu.


    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.

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Bruno Silva 26 Reputation points
    2022-07-11T12:56:14.027+00:00

    @Yonglun Liu (Shanghai Wicresoft Co,.Ltd.) ,

    for example:

    My function of viewmodel:

    public async void OpenPadlock()  
            {  
      
                //DisplayAlert("Message", "Cadeado aberto! ", "Ok");  
                GrantAccessResponse garp = new GrantAccessResponse();  
      
                try  
                {  
                    garp = await vn.RequestAccess(2, "36878811805");  
                }  
                catch (Exception ex)  
                {  
                    txtNow.Text = ex.Message.ToString();  
                }  
      
                  
                if (garp.EventId == 100) //authorized  
                {  
                    //Connect to the device  
                    try  
                    {  
                        if (device != null)  
                        {  
                            await adapter.ConnectToDeviceAsync(device);  
                            txtNow.Text = "Dispositivo conectado";  
                        }  
                        else  
                        {  
                              
                            await DisplayAlert("Message", "Dispositivo não encontrado! ", "Ok");  
                            return;  
                        }  
                    }  
                    catch (DeviceConnectionException ex)  
                    {  
                        //Could not connect to the device  
                        txtNow.Text = ex.Message.ToString();  
                    }  
      
                    //Get Service  
                    try  
                    {  
                        Service = await device.GetServiceAsync(UUID_SERV); //- this guid is nRF device  
                    }  
                    catch (Exception ex)  
                    {  
                        //Could not connect get the service  
                        txtNow.Text = ex.Message.ToString();  
                    }  
      
      
                    //Send some bytes to UART Characteristic  
                    byte[] bytes_WRITE = Encoding.ASCII.GetBytes(secret);  
      
                    try  
                    {  
                        WRITECharacteristic = await Service.GetCharacteristicAsync(UUID_WRITE);  
      
                        await WRITECharacteristic.WriteAsync(bytes_WRITE);  
      
                        txtNow.Text = "Enviando Bytes...";  
                    }  
                    catch (Exception ex)  
                    {  
                        txtNow.Text = ex.Message;  
                    }  
      
                      
                }  
                else  
                {  
                    var json = JsonConvert.SerializeObject(garp);  
                    txtNow.Text = json;  
                }  
      
      
            }  
      
            public async void ScanDevices()  
            {  
                var status = await Permissions.RequestAsync<Permissions.LocationWhenInUse>();  
                var scanFilterOptions = new ScanFilterOptions();  
                scanFilterOptions.ServiceUuids = new[] { UUID_SERV };  
                scanFilterOptions.DeviceNames = new[] { "ASSA ABLOY - CADEADO BLE" };  
      
      
                txtNow.Text = "Buscando...";  
      
                try  
                {  
                    ItemList.Clear();  
                    adapter.DeviceDiscovered += (s, a) =>  
                    {  
                        if (!ItemList.Contains((PadlockInfo)a.Device))  
                            ItemList.Add((PadlockInfo)a.Device);  
                    };  
      
                    //We have to test if the device is scanning   
                    if (!ble.Adapter.IsScanning)  
                    {  
                        await adapter.StartScanningForDevicesAsync(scanFilterOptions);  
      
                    }  
                    if (ItemList.Count() > 0)  
                    {  
                          
                        device = (IDevice)ItemList[0];  
                        txtNow.Text = "Device On-line";  
      
      
                        await DisplayAlert("Alert", "Device List has " + ItemList.Count.ToString() + " elements", "OK");  
                    }  
      
      
                }  
                catch (Exception ex)  
                {  
                    await DisplayAlert("Alert", "Device List has " + ItemList.Count.ToString() + " elements", "OK");  
                }  
      
            }  
    

    OpenPadlock responsible by function to open the padlock
    ScanDevice function by responsible to find the padlock

    Code Behing:

    using System;  
    using System.Collections.Generic;  
    using System.Collections.ObjectModel;  
    using System.ComponentModel;  
    using System.Linq;  
    using System.Text;  
    using System.Threading.Tasks;  
    using System.Timers;  
    using BT.Models;  
    using BT.ViewModels;  
    using Newtonsoft.Json;  
    using Plugin.BLE;  
    using Plugin.BLE.Abstractions;  
    using Plugin.BLE.Abstractions.Contracts;  
    using Plugin.BLE.Abstractions.Exceptions;  
    using Xamarin.Essentials;  
    using Xamarin.Forms;  
      
      
      
    namespace BT.Views  
    {  
     public partial class HomePage : ContentPage  
     {  
              
            private VaultNext vn;  
            private VNUser vnUser; private INavigation navigation;  
            public ObservableCollection<PadlockInfo> ItemList { get; set; }  
            IAdapter adapter;  
            Guid UUID_SERV = Guid.Parse("6e400001-b5a3-f393-e0a9-e50e24dcca9e"); //- this guid is nRF device  
            IBluetoothLE ble;  
            IDevice device;  
            ObservableCollection<IDevice> deviceList;  
            IList<IService> Services;  
            IService Service;  
            string secret = "assaplk\0";  
            ICharacteristic WRITECharacteristic;  
            Guid UUID_WRITE = Guid.Parse("6e400002-b5a3-f393-e0a9-e50e24dcca9e");  
      
            public HomePage (VaultNext _vn, VNUser _vnUser, INavigation navigation)  
            {  
                InitializeComponent();  
                vn = _vn;  
                vnUser = _vnUser;  
                adapter = CrossBluetoothLE.Current.Adapter;  
                adapter.ScanMode = ScanMode.LowLatency;  
                adapter.ScanTimeout = 3000;  
                ble = CrossBluetoothLE.Current;  
                deviceList = new ObservableCollection<IDevice>();  
      
                BindingContext = new HomePageViewModel(vn, vnUser, navigation);  
      
                var status = Permissions.RequestAsync<Permissions.LocationWhenInUse>();  
      
                GridPadlock = new Command(() =>  
                {  
                    var status = Permissions.RequestAsync<Permissions.LocationWhenInUse>();  
                    var scanFilterOptions = new ScanFilterOptions();  
                    scanFilterOptions.ServiceUuids = new[] { UUID_SERV };  
                    scanFilterOptions.DeviceNames = new[] { "ASSA ABLOY - CADEADO BLE" };  
      
      
                    txtNow.Text = "Buscando...";  
      
                    try  
                    {  
                        ItemList.Clear();  
                        adapter.DeviceDiscovered += (s, a) =>  
                        {  
                            if (!ItemList.Contains((PadlockInfo)a.Device))  
                                ItemList.Add((PadlockInfo)a.Device);  
                        };  
      
                        //We have to test if the device is scanning   
                        if (!ble.Adapter.IsScanning)  
                        {  
                            adapter.StartScanningForDevicesAsync(scanFilterOptions);  
      
                        }  
                        if (ItemList.Count() > 0)  
                        {  
      
                            device = (IDevice)ItemList[0];  
                            txtNow.Text = "Device On-line";  
      
      
                             DisplayAlert("Alert", "Device List has " + ItemList.Count.ToString() + " elements", "OK");  
                        }  
      
      
                    }  
                    catch (Exception ex)  
                    {  
                         DisplayAlert("Alert", "Device List has " + ItemList.Count.ToString() + " elements", "OK");  
                    }  
                });  
      
                if (deviceList.Count() == 0)  
                {  
                    ItemList = new ObservableCollection<PadlockInfo>();  
                    ItemList.Add(new PadlockInfo() { IdPadlock = 1, NameDevice = "Cadeado 1", Open = "ABRIR", ImageUrl = "spaceBlue.png", Image2Url = "closedPadlock.png", BateryPadlock = "100%" });  
                    //ItemList.Add(new PadlockInfo() { IdPadlock = 2, NameDevice = "Cadeado 2", Open = "ABRIR", ImageUrl = "spaceBlue.png", Image2Url = "closedPadlock.png", BateryPadlock = "89%" });  
                    //ItemList.Add(new PadlockInfo() { IdPadlock = 2, NameDevice = "Cadeado 3", Open = "ABRIR", ImageUrl = "spaceBlue.png", Image2Url = "closedPadlock.png", BateryPadlock = "90%" });  
                    //ItemList.Add(new PadlockInfo() { IdPadlock = 4, NameDevice = "Cadeado 4", Open = "ABRIR", ImageUrl = "spaceBlue.png", Image2Url = "closedPadlock.png", BateryPadlock = "100%" });  
                    //ItemList.Add(new PadlockInfo() { IdPadlock = 5, NameDevice = "Cadeado 5", Open = "ABRIR", ImageUrl = "spaceBlue.png", Image2Url = "closedPadlock.png", BateryPadlock = "1%" });  
                    //ItemList.Add(new PadlockInfo() { IdPadlock = 6, NameDevice = "Cadeado 6", Open = "ABRIR", ImageUrl = "spaceBlue.png", Image2Url = "closedPadlock.png", BateryPadlock = "99%" });  
                    //ItemList.Add(new PadlockInfo() { IdPadlock = 7, NameDevice = "Cadeado 7", Open = "ABRIR", ImageUrl = "spaceBlue.png", Image2Url = "closedPadlock.png", BateryPadlock = "100%" });  
                    //ItemList.Add(new PadlockInfo() { IdPadlock = 8, NameDevice = "Cadeado 8", Open = "ABRIR", ImageUrl = "spaceBlue.png", Image2Url = "closedPadlock.png", BateryPadlock = "95%" });  
                    //ItemList.Add(new PadlockInfo() { IdPadlock = 9, NameDevice = "Cadeado 9", Open = "ABRIR", ImageUrl = "spaceBlue.png", Image2Url = "closedPadlock.png", BateryPadlock = "5%" });  
                    //ItemList.Add(new PadlockInfo() { IdPadlock = 10, NameDevice = "Cadeado 10", Open = "ABRIR", ImageUrl = "spaceBlue.png", Image2Url = "closedPadlock.png", BateryPadlock = "0%" });  
                    //ItemList.Add(new PadlockInfo() { IdPadlock = 11, NameDevice = "Cadeado 11", Open = "ABRIR", ImageUrl = "spaceBlue.png", Image2Url = "closedPadlock.png", BateryPadlock = "100%" });  
      
      
                    gridLayout.RowDefinitions.Add(new RowDefinition());  
                    gridLayout.RowDefinitions.Add(new RowDefinition());  
                    gridLayout.RowDefinitions.Add(new RowDefinition());  
                    gridLayout.ColumnDefinitions.Add(new ColumnDefinition());  
                    gridLayout.ColumnDefinitions.Add(new ColumnDefinition());  
      
      
                    var productIndex = 0;  
                    for (int rowIndex = 0; rowIndex < ItemList.Count; rowIndex++)  
                    {  
                        for (int columnIndex = 0; columnIndex < 2; columnIndex++)  
                        {  
                            if (productIndex >= ItemList.Count)  
                            {  
                                break;  
                            }  
                            var product = ItemList[productIndex];  
                            productIndex += 1;  
                            var imagebackground = new Image  
                            {  
                                Source = product.ImageUrl,  
                                WidthRequest = 180,  
                                Margin = new Thickness(0, 13, 0, 0),  
      
      
      
                            };  
                            var padlock = new ImageButton  
                            {  
                                Source = product.Image2Url,  
                                HorizontalOptions = LayoutOptions.Center,  
                                BorderColor = Color.Transparent,  
                                BackgroundColor = Color.Transparent,  
                                WidthRequest = 40  
      
      
                            };  
                            padlock.Clicked += OnImageButtonClicked;  
      
                            var namepadlock = new Label  
                            {  
                                Text = product.NameDevice,  
                                FontAttributes = FontAttributes.Bold,  
                                TextColor = Color.Black,  
                                Margin = new Thickness(65, -2, 0, 0)  
      
                            };  
                            var open = new Label  
                            {  
                                Text = product.Open,  
                                HorizontalOptions = LayoutOptions.Center,  
                                FontSize = 13,  
                                Margin = new Thickness(118, 30, 0, 0),  
                                TextColor = Color.Black,  
                                FontAttributes = FontAttributes.Bold  
                            };  
                            var baterypadlock = new Label  
                            {  
                                Text = product.BateryPadlock,  
                                HorizontalOptions = LayoutOptions.Center,  
                                FontSize = 13,  
                                Margin = new Thickness(118, 23, 0, 0),  
                                TextColor = Color.Black,  
                                FontAttributes = FontAttributes.Bold  
                            };  
      
      
                            gridLayout.Children.Add(namepadlock, columnIndex, rowIndex);  
                            gridLayout.Children.Add(open, columnIndex, rowIndex);  
                            gridLayout.Children.Add(imagebackground, columnIndex, rowIndex);  
                            gridLayout.Children.Add(padlock, columnIndex, rowIndex);  
                            gridLayout.Children.Add(baterypadlock, columnIndex, rowIndex);  
                        }  
                    }  
                }  
                else  
                {  
                    txtNow.Text = "Não à nenhum cadeado disponivel";  
                }  
      
      
      
            }  
      
            public Command GridPadlock { get; set; }  
      
            void OnImageButtonClicked(object sender, EventArgs e)  
            {  
                OpenPadlock();  
                //DisplayAlert("Message","Cadeado Aberto","Ok");  
                             
            }   
    }  
    

    }

    So I have these two functions in the viewmodel,
    which looks for and opens the padlock, and in the code behind where it creates the grid structure, I would need to know if there is a way to extract these two functions from the viewmodel and run them in the code behind


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.