How to get the bindable data from View MAUI

Chinmay Dole 40 Reputation points
2024-05-14T12:14:20.2066667+00:00

I have a code snippet below where I dynamically add data to StackLayout. For Xamarin Forms using BindingContext, I could access the data bound to the view. But this is not possible in.net MAUI. Is there any documentation for the same?

public class MyData {     
	
	public string Name { get; set; }     
	public int Age { get; set; } 

}
StackLayout _content = new StackLayout { HeightRequest = 0, HorizontalOptions = LayoutOptions.FillAndExpand, IsVisible = false };

foreach (var child in _content.Children)

{   
   if (child.BindingContext is MyData data){

           string name = data.Name;

           int age = data.Age;

   }
}
.NET MAUI
.NET MAUI
A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
3,008 questions
0 comments No comments
{count} votes

Accepted answer
  1. Leon Lu (Shanghai Wicresoft Co,.Ltd.) 69,691 Reputation points Microsoft Vendor
    2024-05-15T01:10:10.6233333+00:00

    Hello,

    Is there any documentation for the same?

    You can still use BindingContext , before you use it, please set specific type of the child property to the Microsoft.Maui.Controls.View, then you can use child.BindingContext.

    foreach (Microsoft.Maui.Controls.View child in _content.Children)
    {
         if (child.BindingContext is MyData data)
         {
     
             string name = data.Name;
     
             int age = data.Age;
     
         }
    }
    

    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.

    2 people found this answer helpful.

0 additional answers

Sort by: Most helpful