问题
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