Xamarin.Forms可以创建类型相关的数据表吗?

时间:2017-11-10 04:44:28

标签: xaml xamarin.forms controls declarative

在WPF中,您可以创建一个DataTemplate,将其放在ResourceDictionary中,为其分配一个Type,然后将该类型的数据绑定到ContentControl,DataTemplate将用于呈现。如在这个例子中: How do I use the DataType property on a WPF DataTemplate?

Xamarin.Forms企业应用程序电子书暗示了这种能力,但没有显示任何示例:https://developer.xamarin.com/guides/xamarin-forms/enterprise-application-patterns/mvvm/#Creating_a_View_Defined_as_a_Data_Template

可以在Xamarin.Forms中完成吗?

2 个答案:

答案 0 :(得分:0)

您可以将数据模板创建为资源或类型(以及内联)。

以下是有关如何操作的详细信息。

https://developer.xamarin.com/guides/xamarin-forms/application-fundamentals/templates/data-templates/creating/

您还可以创建模板选择器并使用它。

https://xamarinhelp.com/xamarin-forms-datatemplateselector/

答案 1 :(得分:0)

很遗憾,x:DataType无法使用Xamarin Forms。 (我尝试了许多不同的方法,但是失败了。)

您应该实现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;
    }
}

这里是Microsoft document

相关问题