Xamarin DataTemplate与代码背后的绑定不起作用 [英] Xamarin datatemplate with bindings in code behind not working

查看:78
本文介绍了Xamarin DataTemplate与代码背后的绑定不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在我的应用程序中创建一个页面,该页面中的所有控件都是通过后面的C#代码动态生成的.我正在使用Nuget包DLToolkit, flowlist创建流列表.

I have tried to make a page in my app where all controls are generated dynamically via C# code behind. I am using a Nuget Packages, DLToolkit, flowlist to create a flow list.

在使用 Xaml 之前,我已经在我的项目中使用了此软件包,该软件包可以正常使用. 但是,当我尝试在后面的代码中创建datatemplate时,它仅显示一个空白控件,但是将鼠标悬停在该控件上方时,您会看到其中确实有项目.

I have already used this package in my project before using Xaml, and it fully works. However when I try to create a datatemplate in code behind, it just displays a blank control, however when hovering above this control, you can see there's actually items in it.

我的问题是:我该如何在后面的代码中创建带有数据绑定的数据模板?

这是一个示例,可以在 Xaml 中使用:

Here is an example and works in Xaml:

<flv:FlowListView x:Name="flvList" BackgroundColor="White" FlowColumnCount="3" FlowItemsSource="{Binding LstItemSource}" HasUnevenRows="True">
            <flv:FlowListView.FlowColumnTemplate>
                <DataTemplate>

                    <StackLayout BackgroundColor="White" Padding="2" HorizontalOptions="FillAndExpand">

                        <Frame  Margin="20" Padding="0" HeightRequest="175" OutlineColor="Gray" BackgroundColor="White" CornerRadius="10" HasShadow="True" IsClippedToBounds="True">
                            <Frame.Content>

                                <AbsoluteLayout HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" >
                                    <Image Aspect="AspectFill" AbsoluteLayout.LayoutBounds="1,1,1,1" AbsoluteLayout.LayoutFlags="All"  Source="{Binding BgImage}" />
                                    <BoxView Color="Black" Opacity=".5"  AbsoluteLayout.LayoutBounds="1,1,1,1" AbsoluteLayout.LayoutFlags="All"/>
                                    <StackLayout Margin="20" VerticalOptions="CenterAndExpand" HorizontalOptions="CenterAndExpand">
                                        <Label Text="{Binding SubTitle}"  FontSize="Medium" TextColor="#66FFFFFF"/>
                                        <Label Text="{ Binding Title}" FontSize="Large" TextColor="White" />
                                    </StackLayout>
                                </AbsoluteLayout>

                            </Frame.Content>
                        </Frame>

                    </StackLayout>

                </DataTemplate>
            </flv:FlowListView.FlowColumnTemplate>
        </flv:FlowListView>

但是,在此项目中生成了控件,因此没有涉及 Xaml 的代码. 这是我在后面的代码中尝试过的代码示例,但是不起作用:

However, in this project the controls are generated, so there is no Xaml code involved. This is an example of the code that I've tried in code behind, but doesn't work:

#region Datatemplate
            var dataTemplate = new DataTemplate(() =>
            {
                var StackLayout = new StackLayout { BackgroundColor = Color.Pink, Padding = 2, HorizontalOptions = LayoutOptions.FillAndExpand };

                #region children/content for frame
                AbsoluteLayout absoluteLayout = new AbsoluteLayout { HorizontalOptions = LayoutOptions.FillAndExpand, VerticalOptions = LayoutOptions.FillAndExpand };


                #region content for AbsoluteLayout
                var imgBg = new Image();
                AbsoluteLayout.SetLayoutBounds(imgBg , new Rectangle(1, 1, 1, 1));
                AbsoluteLayout.SetLayoutFlags(imgBg , AbsoluteLayoutFlags.All);

                imgBg .SetBinding(Image.SourceProperty, "BgImage");
                absoluteLayout.Children.Add(imgBg );


                var overlayBox = new BoxView { Color = Color.Black, Opacity = 0.5 };
                AbsoluteLayout.SetLayoutBounds(overlayBox, new Rectangle(1, 1, 1, 1));
                AbsoluteLayout.SetLayoutFlags(overlayBox, AbsoluteLayoutFlags.All);
                absoluteLayout.Children.Add(overlayBox);


                #region InnerStackpanel
                StackLayout innerStackVoorAbsoluteLayout = new StackLayout { Margin = new Thickness(20), VerticalOptions = LayoutOptions.CenterAndExpand, HorizontalOptions = LayoutOptions.CenterAndExpand };

                var lblTitel = new Label { FontSize = Device.GetNamedSize(NamedSize.Medium, typeof(Label)), TextColor = Color.White };
                var lblSubTitel = new Label { FontSize = Device.GetNamedSize(NamedSize.Medium, typeof(Label)), TextColor = Color.White };


                //Bindings 
                lblTitel.SetBinding(Label.TextProperty, "Title");
                lblSubTitel.SetBinding(Label.TextProperty, "SubTitle");

                innerStackVoorAbsoluteLayout.Children.Add(lblSubTitel);
                innerStackVoorAbsoluteLayout.Children.Add(lblTitel);

                absoluteLayout.Children.Add(innerStackVoorAbsoluteLayout);
                #endregion

                #endregion


                #endregion

                Frame frame = new Frame();
                frame.Content = absoluteLayout;



                StackLayout.Children.Add(frame);


                return StackLayout;
            });

            #endregion


            FlowListView lstRelatieLijst = new FlowListView();
            lstRelatieLijst.ItemsSource = lstRelatieItems;
            lstRelatieLijst.FlowColumnTemplate = dataTemplate;
            lstRelatieLijst.BackgroundColor = Color.LightGoldenrodYellow;
            lstRelatieLijst.FlowColumnCount = 1;
            lstRelatieLijst.HasUnevenRows = true;


            #endregion

请问有人可以给我一些建议,让我像后面的代码中的上层 Xaml 一样吗?

Can someone give me some advice how I can become something similar like the upper Xaml in code behind, please?

我已经尝试了以下来源,但不幸的是,我没有按预期工作.我希望看到相同的结果或类似的XAML代码.但是在关注他们的信息之后,FLowListView似乎为空:

I already tried the following sources but unfortunately I doesn't work as expected. I hoped to see the same result or something similar like the XAML code. But after following their info,the FLowListView appears to be empty:

https://docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/templates/data-templates/creating

https://www.codeproject.com/Questions/516614/createplusdatatemplatepluscodeplusbehind

推荐答案

您应该使用

flowList.SetBinding(FlowListView.FlowItemsSourceProperty, "List");而不是ItemsSource

这是工作示例....

using DLToolkit.Forms.Controls;
using System;
using Xamarin.Forms;

namespace FlowListTest
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
            LoadUI();
            BindingContext = new BContext();
        }

        private void LoadUI()
        {
            var dataTemplate = new DataTemplate(() =>
            {
                var image = new Image();
                image.SetBinding(Image.SourceProperty, "BgImage");

                var titleLabel = new Label
                {
                    FontSize = Device.GetNamedSize(NamedSize.Medium, typeof(Label)),
                    TextColor = Color.White,
                };
                titleLabel.SetBinding(Label.TextProperty, "Title");

                var subTitleLabel = new Label
                {
                    FontSize = Device.GetNamedSize(NamedSize.Medium, typeof(Label)),
                    TextColor = Color.White,
                };
                subTitleLabel.SetBinding(Label.TextProperty, "Subtitle");

                return new StackLayout
                {
                    BackgroundColor = Color.Pink,
                    Padding = 2,
                    HorizontalOptions = LayoutOptions.FillAndExpand,
                    Children = {
                        new Frame {
                            Content = new AbsoluteLayout {
                                 HorizontalOptions = LayoutOptions.FillAndExpand,
                                 VerticalOptions = LayoutOptions.FillAndExpand,
                                 Children = {
                                    image,
                                    new StackLayout {
                                         Margin = new Thickness(20),
                                         VerticalOptions = LayoutOptions.CenterAndExpand,
                                         HorizontalOptions = LayoutOptions.CenterAndExpand,
                                         Children = {
                                            titleLabel,
                                            subTitleLabel
                                         }
                                    }
                                 }
                            }
                        }
                    }
                };
            });

            var flowList = new FlowListView();
            flowList.SetBinding(FlowListView.FlowItemsSourceProperty, "List");
            flowList.FlowColumnTemplate = dataTemplate;
            flowList.BackgroundColor = Color.LightGoldenrodYellow;
            flowList.FlowColumnCount = 1;
            flowList.HasUnevenRows = true;

            var button = new Button { Text = "Add" };
            button.Clicked += Button_Clicked
            ;
            Content = new StackLayout
            {
                Children = {
                    button,
                    flowList
                }
            };

        }

        private void Button_Clicked(object sender, EventArgs e)
        {
            (BindingContext as BContext).Add();
        }
    }

    public class Foo
    {
        public string BgImage { get; set; }
        public string Title { get; set; }
        public string Subtitle { get; set; }
    }

    public class BContext
    {
        public FlowObservableCollection<Foo> List { get; set; }

        public BContext()
        {
            List = new FlowObservableCollection<Foo>
            {
                new Foo {
                    BgImage = "http://via.placeholder.com/350x150",
                    Title = "Title",
                    Subtitle = "SubTitle"
                },
                new Foo {
                    BgImage = "http://via.placeholder.com/350x150",
                    Title = "Title1",
                    Subtitle = "SubTitle1"
                }
            };
        }

        public void Add()
        {
            List.Add(new Foo
            {
                BgImage = "http://via.placeholder.com/350x150",
                Title = "Title" + List.Count,
                Subtitle = "SubTitle" + List.Count
            });
        }
    }
}

这篇关于Xamarin DataTemplate与代码背后的绑定不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆