Search code examples
c#staticmaui

MAUI C# - Find view by name in static method


I'm beginning in MAUI C# (I always used VB.NET) and I try to build a scheduler app. First, I made a custom control that creates a view(absolute layout with borders and labels)

CustomControl

On border clicked, I want to fire method in the main page to send the ID of the border control

    private void PointerGestureRecognizer_PointerPressed(object sender, PointerEventArgs e)
{
MainPage.lblChange(id);
}

I add my custom control in my main page and the method to get the ID of the selected control

public MainPage()
{
    InitializeComponent();
   for(i=0;i<10;i++)
  {
   //Add custom crontrol.....
   }
}
 
public static void lblChange(string lab)
{
Border border=(Border) myView.FindByName(lab);
....
}

For me, I need to make the method 'lblChange' static. In this case, I have an error :

ERROR

Could you help me please ?


Solution

  • You can try the following code:

    public partial class MainPage : ContentPage
    {
        public static ScrollView views;
    
        public MainPage()
        {
            InitializeComponent();
            views = myView;
        }
    
        public static void lblChange(string lab)
        {
            Border border =(Border)views.FindByName(lab);
            .....
        }
    
        .......
    
    }