Xamarin.Forms可以制作与类型相关的数据模板吗? [英] Xamarin.Forms can you make type related datatemplates?

查看:84
本文介绍了Xamarin.Forms可以制作与类型相关的数据模板吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在WPF中,您可以创建一个DataTemplate,将其放入ResourceDictionary中,为其分配一个Type,然后将该类型的数据绑定到ContentControl,然后将使用DataTemplate进行呈现.如本例所示:在WPF上如何使用DataType属性数据模板?

In WPF you can create a DataTemplate, put it in a ResourceDictionary, assign it a Type and then bind data of that type to a ContentControl and the DataTemplate will be used to render. as in this example: How do I use the DataType property on a WPF DataTemplate?

Xamarin.Forms企业应用程序电子书暗示了这种能力,但未显示任何示例:

the Xamarin.Forms enterprise apps ebook hints at such an ability but does not show any example: https://developer.xamarin.com/guides/xamarin-forms/enterprise-application-patterns/mvvm/#Creating_a_View_Defined_as_a_Data_Template

这可以在Xamarin.Forms中完成吗?

Can this be done in Xamarin.Forms?

推荐答案

不幸的是, x:DataType 不适用于Xamarin Forms.(我尝试了许多不同的方法,但都失败了.)

Unfortunately, x:DataType does not working with Xamarin Forms. (I tried many different ways, but fail.)

您应该实现 DataTemplateSelector

You should implement DataTemplateSelector

<ResourceDictionary xmlns="http://xamarin.com/schemas/2014/forms"
                    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                    xmlns:forms="clr-namespace:Solution.Forms"
                    x:Class="Mango.Forms.LayerDataTemplate">

    <!--#region RectLayerView -->
    <DataTemplate x:Key="RectLayerDataTemplate">
        <forms:RectLayerView forms:ValueX="{Binding ValueX}"
                             forms:ValueY="{Binding ValueY}"
                             forms:ValueWidth="{Binding ValueWidth}"
                             forms:ValueHeight="{Binding ValueHeight}"
                             forms:MangoColor="{Binding Color}" />
    </DataTemplate>
    <!--#endregion-->
    
    <forms:LayerDataTemplateSelector x:Key="LayerDataTemplateSelector"
                                     RectLayerTemplate="{StaticResource RectLayerDataTemplate}"/>
</ResourceDictionary>

DataTemplateSelector.cs

public class LayerDataTemplateSelector : DataTemplateSelector
{
    public DataTemplate RectLayerTemplate { get; set; }

    protected override DataTemplate OnSelectTemplate(object item, BindableObject container)
    {
        if (item is RectLayerViewModel)
            return RectLayerTemplate;

        return null;
    }
}

这里是 Microsoft文档

这篇关于Xamarin.Forms可以制作与类型相关的数据模板吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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