【问题标题】:Xamarin.Forms: Create instance of a DataTemplateXamarin.Forms:创建 DataTemplate 的实例
【发布时间】:2016-12-20 11:12:53
【问题描述】:

我不想创建BindableProperty 类型为DataTemplateContentView,这样当我使用自定义ContentView 时,我可以自定义元素的外观。

但我不想在代码中安排和创建内容,如何从 DataTemplate 创建实例?

例如,在我的自定义视图中,我有一个对象集合,现在对于每个对象,我想基于设置的数据模板创建一个视图,并将创建的视图的绑定上下文设置为该对象。

【问题讨论】:

    标签: xamarin xamarin.forms


    【解决方案1】:

    我通过以下方式解决了。

    我以下列方式使用我的自定义ContentView

            <controls:MyCustomView Items="{Binding SampleItems}">
                <controls:MyCustomView.ItemTemplate>
                    <DataTemplate>
                        <Label Text="{Binding SampleProperty}" />
                    </DataTemplate>
                </controls:MyCustomView.ItemTemplate>
            </controls:MyCustomView>
    

    然后在MyCustomView 后面的代码中声明一个ItemTemplate 可绑定属性:

        public DataTemplate ItemTemplate
        {
            get { return (DataTemplate)GetValue(ItemTemplateProperty); }
            set { SetValue(ItemTemplateProperty, value); }
        }
    
        public static readonly BindableProperty ItemTemplateProperty = BindableProperty.Create(
            nameof(ItemTemplate),
            typeof(DataTemplate),
            typeof(MyCustomView),
            propertyChanged: (bObj, oldValue, newValue) =>
            {
                var view = bObj as MyCustomView;
                if (view != null)
                    view.SampleMethodToArrangeItems();
            }
        );
    

    现在假设在我要创建和排列的SampleMethodToArrangeItems 方法中,从提供的数据模板创建的项目:

            foreach (var item in Items)
            {
                var itemView = ItemTemplate.CreateContent() as View;
                if (itemView != null)
                {
                    itemView.BindingContext = item;
                    // Do something with the create view e.g. add it to Grid.Children
                }
            }
    

    【讨论】:

    • 你能发布完整的渲染器吗?理解起来有点混乱......提前谢谢
    猜你喜欢
    • 2012-09-15
    • 2012-11-17
    • 2020-06-05
    • 2019-05-05
    • 1970-01-01
    • 2018-07-23
    • 1970-01-01
    • 2020-07-22
    • 2019-06-30
    相关资源
    最近更新 更多