Dynamically Editing DataTemplate in MAUI

Dynamically editing DataTemplate in MAUI

XAML code:
Source="{Binding}" indicates direct binding to the parent context object, typically used when the parent source is a string.

1
2
3
4
<DataTemplate>
    <Image Source="{Binding}" HorizontalOptions="Center" VerticalOptions="Center"
           Aspect="AspectFit" HeightRequest="60" />
</DataTemplate>

c# code

1
2
3
4
5
6
7
var dataTemplate = new DataTemplate(() =>
{
    var image = new Microsoft.Maui.Controls.Image();
    var b = new Binding();
    image.SetBinding(Microsoft.Maui.Controls.Image.SourceProperty, b);
    return image;
});
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
var personDataTemplate = new DataTemplate(() =>
{
    var grid = new ContentView();
    var nameLabel = new Label { FontAttributes = FontAttributes.Bold };
    var ageLabel = new Label();
    var locationLabel = new Label { HorizontalTextAlignment = TextAlignment.End };

    nameLabel.SetBinding(Label.TextProperty, new Binding());
    ageLabel.SetBinding(Label.TextProperty, "Age");
    locationLabel.SetBinding(Label.TextProperty, "Location");
    grid.Content = nameLabel;
    //grid.LoadFromXaml(@"<Label Text=""{Binding}"" HorizontalOptions=""Center"" VerticalOptions=""Center""
    //                           TextColor=""Black"" />");
    //grid.Children.Add(ageLabel);
    //grid.Children.Add(locationLabel);

    return grid;//  new ContentView { View = grid };
});
Licensed under CC BY-NC-SA 4.0
Built with Hugo
Theme Stack designed by Jimmy