微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Xamarin.Forms DataTemplateSelector 在 iOS 上不起作用未调用构造函数

如何解决Xamarin.Forms DataTemplateSelector 在 iOS 上不起作用未调用构造函数

我像这样膨胀数据模板选择器:

<ContentPage.Resources>
    <ResourceDictionary>
        <local:MyDataTemplateSelector x:Key="templateSelector"></local:MyDataTemplateSelector>
    </ResourceDictionary>
</ContentPage.Resources>

            <Grid Grid.Row="0"   >

                <abstractions:CarouselViewControl VerticalOptions="Start"  x:Name="carouselview" ItemTemplate="{StaticResource templateSelector}" />

            </Grid>

代码如下:

    public MyDataTemplateSelector()
    {
        Layout1 = new DataTemplate(typeof(CV_CarouselView_ShowPics));
        Layout2 = new DataTemplate(typeof(CV_VideoPlayer));
    }

    protected override DataTemplate OnSelectTemplate(object item,BindableObject container)
    {
        FullAdType cell = (FullAdType)item;

        if(cell != null && cell.hasVideo )
        {

            return Layout2; // get video layout 

        }

        else
            return Layout1;

    }

但是这两个数据模板选择器构造函数都没有在 iOS 上调用,但在 Android 上,它工作得很好。

这里有什么问题?

谢谢

解决方法

我们经常在 xaml 、check here 中定义 DataTemplate

 <ContentPage.Resources>
        <DataTemplate x:Key="AmericanMonkeyTemplate">
            ...
        </DataTemplate>

        <DataTemplate x:Key="OtherMonkeyTemplate">
            ...
        </DataTemplate>

        <controls:MonkeyDataTemplateSelector x:Key="MonkeySelector"
                                             AmericanMonkey="{StaticResource AmericanMonkeyTemplate}"
                                             OtherMonkey="{StaticResource OtherMonkeyTemplate}" />
    </ContentPage.Resources>

    <CarouselView ItemsSource="{Binding Monkeys}"
                  ItemTemplate="{StaticResource MonkeySelector}" />

但是,如果您想在后面的代码中初始化 DataTemplate,则可以在数据模板选择器构造函数中创建它们。

public PersonDataTemplateSelector()
        {
            ValidTemplate = new DataTemplate(()=> {

                var grid = new Grid();

                var nameLabel = new Label { FontAttributes = FontAttributes.Bold };
                nameLabel.TextColor = Color.Green;
                nameLabel.SetBinding(Label.TextProperty,"Name");
                grid.Children.Add(nameLabel);

                return grid ;
            });

            InvalidTemplate = new DataTemplate(() => {

                var grid = new Grid();

                var nameLabel = new Label {  };
                nameLabel.TextColor = Color.Red;
                nameLabel.SetBinding(Label.TextProperty,"Name");
                grid.Children.Add(nameLabel);

                return grid ;
            });

        }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。