Xamarin.Forms can you make type related datatemplates?

随声附和 提交于 2021-02-10 19:52:31

问题


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?

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

Can this be done in Xamarin.Forms?


回答1:


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

You should implement DataTemplateSelector

ResourceDictionary.xaml

<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;
    }
}

Here is Microsoft document



来源:https://stackoverflow.com/questions/47215805/xamarin-forms-can-you-make-type-related-datatemplates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!