代码动态编辑DataTemplate

代码动态编辑DataTemplate

xaml代码 Source="{Binding}" 表示直接绑定父级的上下文对象,一般用在父级源是字符串的情况。

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

c#代码

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